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 had 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"
}
]}
This is 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);
}
}
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
}
]}
Update
At the time of writing this it had slipped my mind that StringEnumConverter existed. If you would like to retain readable names in your JSON model
[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 { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public ItemTypes ItemType { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public SlotTypes SlotType { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With