我正在尝试使用 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);
}
}
您的 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
}
]}
更新
在撰写本文时,我忘记了 StringEnumConverter
的存在。如果您想在 JSON 模型中保留可读的名称
[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; }
}
我是一名优秀的程序员,十分优秀!