- Home /
Using Enums with JSON
Hey guys.
I am trying to use JSON to create an item database for my project.
The database contains JSON data like this:
{
"id": 0,
"title": "Rock",
"weight": 5,
"stackable": true
"type": "Material"
}
My Item class is here:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using System.IO;
[System.Serializable]
public class ItemDatabase : MonoBehaviour
{
public List<Item> database = new List<Item>();
private JsonData itemData;
public void Start()
{
itemData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Items.json"));
ConstructItemDatabase();
Debug.Log(database[0].Title);
}
private void ConstructItemDatabase()
{
for(int i = 0; i<itemData.Count; i++)
{
database.Add(new Item((int)itemData[i]["id"], itemData[i]["title"].ToString(), (int)itemData[i]["weight"], (bool)itemData[i]["stackable"];
}
}
}
public class Item
{
public int ID { get; set; }
public string Title { get; set; }
public int Weight { get; set; }
public bool Stackable { get; set; }
public enum ItemType
{
Material,
Weapon,
Medical,
Food
}
public ItemType Type { get; set; }
public Item(int id, string title, int weight, bool stackable, ItemType type)
{
this.ID = id;
this.Title = title;
this.Weight = weight;
this.Stackable = stackable;
this.Type = type;
}
public Item()
{
}
}
So, I want to fetch the Item Type from the JSON file, but I have no idea how to actually get this information. It eventually goes into the ConstructItemDatabase method, like the other values, but how do I get the string for the itemtype from the JSON file "into" the newly generated item as it's type?
Any help is appreciated. Thanks in advance :)
Your answer
Follow this Question
Related Questions
Unknown identifier: 'types'. js(38,61) 1 Answer
cannot convert UnityEngine.Gameobject to GameObject - What's the difference? 1 Answer
InvalidCastException with .net datatypes but not with UnityEngine.Object 1 Answer
How to make a custom type's contents modifiable in an array by inspector? 1 Answer
C# return question 1 Answer