实例代码:
Json文件,Item.json
{
"Infolist":
[
{
"id":1,
"name":"血瓶",
"type":"Consumable",
"description":"回血用",
"capacity":10,
"buyPrice":10,
"sellPrice":5,
"hp":10,
"mp":0,
"sprites":"Sprites/Items/hp"
}
],
"total": 2
}
C#
[Serializable]
public class ItemInfo //数据模板类
{
public int id;
public string name;
public string type;
public string description;
public int capacity;
public int buyPrice;
public int sellPrice;
public string sprites;
public int hp;
public int mp;
}
public class ItemData //数据接收类
{
public List<ItemInfo> Infolist;
public int total;
}
public class Test //测试类
{
private void Start()
{
ParseItemJson();
}
private void ParseItemJson()
{
TextAsset itemText = Resources.Load<TextAsset>("Item"); //从Resources文件夹下直接加载json文件
string itemJson = itemText.text;
ItemData data=JsonUtility.FromJson<ItemData>(itemJson);
Debug.Log(data.total);
foreach (ItemInfo info in data.Infolist)
{
Debug.Log(info.id);
Debug.Log(info.name);
Debug.Log(info.type);
Debug.Log(info.description);
Debug.Log(info.capacity);
Debug.Log(info.buyPrice);
Debug.Log(info.sellPrice);
Debug.Log(info.hp);
Debug.Log(info.mp);
Debug.Log(info.sprites);
}
}
}
其中需要注意的是,数据接收类中的集合对象名字需要和json文件中的数组名(Infolist)相同,数据模板类中的每个变量的名字也需要和json文件中的字段一一对应,建议直接复制粘贴,其中数据模板类需要加上[Serializable]标签
踩坑1:因为json文件中没办法写枚举类型,只有字符串和数字,所以,数据模板类中的变量类型也需要保持一致,不能使用枚举类型,然后在解析json的时候,需要将得到的字符串转换为枚举类型