使用枚举类型的JSON反序列化

时间:2016-11-25 20:22:20

标签: c# json unity3d enums

我正在尝试使用UnityEngine.JsonUtility从文件中反序列化我的json项。它工作正常,但我的枚举类型没有得到正确的转换。我尝试使用EnumMember属性,但仍然没有运气。

我该如何解决?

注意

我正在使用this解决方案来读取多个文件并将它们存储在数组中。

[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;
}

和json文件

{
"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"
}
]}

这是我加载json文件的类:

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);
    }
}

1 个答案:

答案 0 :(得分:0)

您的JSON属性都是字符串,因此它们只能反序列化为String,而Enum值实际上是整数。

您应该能够将JSON更改为以下内容,并且它会反序列化

{
    "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
    }
]}