mashinkata mashinkata - 14 days ago 5
C# Question

JSON deserializion with enum types

I'm trying to deserialize my json items from a file using

UnityEngine.JsonUtility
it works fine but my enum types are not getting properly converted I tried using the
EnumMember
attribute but still no luck how can I fix that ?

Note

I'm using this solution to read multiple files and store them in array.

[Serializable]
public class EquipementItem
{
public enum ItemTypes
{
None,
Armor,
Weapon
}

public enum SlotTypes
{
Head,
Shoulders,
Chest,
Bracers,
Gloves,
Waist,
Legs,
Boots,
Weapon
}

public int ID;
public string Name;

public ItemTypes ItemType;
public SlotTypes SlotType;
}


And the json file

{
"Items": [
{
"ID": "1",
"Name": "Basic Sword",
"ItemType": "Weapon",
"SlotType": "Weapon"
},
{
"ID": "2",
"Name": "Advanced Sword",
"ItemType": "Weapon",
"SlotType": "Weapon"
},
{
"ID": "3",
"Name": "Leather Chest",
"ItemType": "Armor",
"SlotType": "Chest"
}
]}


The class where I load the json file

public class Items : MonoBehaviour
{
public static EquipementItem[] EquipableItems;

private void Awake()
{
string jsonFile = File.ReadAllText(Application.dataPath + "/Scripts/Databases/EquipableItemsDB.json");
EquipableItems = JsonHelper.FromJson<EquipementItem>(jsonFile);
}
}

Answer

Your JSON properties are all strings and so they can only be deserialized to a String, while Enum values are actually integers.

You should be able to change your JSON to the following and it'll deserialize just fine

{
    "Items": [
    {
      "ID": "1",
      "Name": "Basic Sword",
      "ItemType": 2,
      "SlotType": 8
    },
    {
      "ID": "2",
      "Name": "Advanced Sword",
      "ItemType": 2,
      "SlotType": 8
    },
    {
      "ID": "3",
      "Name": "Leather Chest",
      "ItemType": 1,
      "SlotType": 2
    }
]}