转载自:https://www.cnblogs.com/guxin/p/unity-use-jsonobject-parse-json.html
【Unity】使用JSONObject解析Json
为何要用JSONObject
之前已经用过JsonUtility和Newton.Json来解析Json了,为什么现在又要用一个新的JSONObject来解析Json?
- 使用JsonUtility:http://www.cnblogs.com/guxin/p/unity-jsonutility-parse-list-object.html
- 使用Newton.Json:http://www.cnblogs.com/guxin/p/csharp-parse-json-by-newtonsoft-json-net.html
在Unity游戏开发中,使用Newton.Json来反序列化时,需要指定确定的类型,这会带来什么问题?
在游戏的道具系统中,有一个父类Item类,包含属性ID和Name,有一个子类Consumable消耗品类,包含属性HP和MP,UML如下:
后端返回的物品信息Json如下:
[
{
"id": 1,
"name": "血瓶",
"type": "Consumable",
"hp": 10,
"mp": 0,
},
{
"id": 2,
"name": "蓝瓶",
"type": "Consumable",
"hp": 0,
"mp": 10,
}
]
使用Newton.Json时,代码如下:
// itemsJson是包含了物品信息的Json字符串
public void ParseItemJson(string itemsJson)
{
List<Item> itemList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Item>>(itemsJson);
foreach (Item temp in itemList)
{
int id = temp.ID;
string name = temp.Name;
Item.ItemType type = temp.Type;
Item item = null;
switch (type)
{
case Item.ItemType.Consumable:
Consumable consumable = temp as Consumable;
int hp = consumable.HP;
int mp = consumable.MP;
item = new Consumable(id, name, type, hp, mp);
break;
// 其他类型省略。。。
default:
break;
}
itemList.Add(temp);
}
}
按照以上思路,先以Item类型来反序列化,然后根据Item.Type来判断物品类的具体子类型,如果为Consumable消耗品类型,就获取该类型的HP和MP属性,再按消耗品类型来实例化对象。
但是由于反序列化时指定为Item类型,所以即便Json字符串中包含了HP和MP的内容,也不会被解析到Item对象身上。
所以问题是:解析为父类时,再想根据父类中的属性来转型为子类,会导致转型失败!
JSONObject怎么用
现在改用JSONObject,可以解决该问题。
首先在AssetStore中下载JSONObject并导入到Unity项目中。
根据它的ReadMe以及里面自带的Demo,可以快速学习使用该插件。代码修改为如下:
private List<Item> itemList = new List<Item>();
/// <summary>
/// 解析物品Json
/// </summary>
public void ParseItemJson(string itemsJson)
{
JSONObject j = new JSONObject(itemsJson);
foreach (JSONObject temp in j.list)
{
int id = (int)temp["id"].n;
string name = temp["name"].str;
Item.ItemType type = (Item.ItemType)System.Enum.Parse(typeof(Item.ItemType), temp["type"].str);
Item item = null;
switch (type)
{
case Item.ItemType.Consumable:
int hp = (int)temp["hp"].n;
int mp = (int)temp["mp"].n;
item = new Consumable(id, name, type, hp, mp);
break;
// 其他类型省略
default:
break;
}
Debug.Log("item.id = " + item.ID + " , consumable.hp = " + ((Consumable)item).HP);
itemList.Add(item);
}
}
运行后可以正确解析Json,拿到父类和子类的属性值。
http://www.sikiedu.com/course/40/task/545/show