为何要用JSONObject

之前已经用过JsonUtility和Newton.Json来解析Json了,为什么现在又要用一个新的JSONObject来解析Json?

在Unity游戏开发中,使用Newton.Json来反序列化时,需要指定确定的类型,这会带来什么问题?

在游戏的道具系统中,有一个父类Item类,包含属性ID和Name,有一个子类Consumable消耗品类,包含属性HP和MP,UML如下:

后端返回的物品信息Json如下:

[
{
"id": ,
"name": "血瓶",
"type": "Consumable",
"hp": ,
"mp": ,
},
{
"id": ,
"name": "蓝瓶",
"type": "Consumable",
"hp": ,
"mp": ,
}
]

使用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,拿到父类和子类的属性值。


学习资料:

【Unity】使用JSONObject解析Json的更多相关文章

  1. JSONObject解析json数据

    首先先看一下我们要解析的json数据是什么样子的: 代码: String url="http://113.57.190.228:8001/Web/Report/GetBigMSKReport ...

  2. 浅谈JSONObject解析JSON数据

    我们在做jmeter接口测试时能会用beanshell断言,一般都会将返回值转成JSONObject对象进行处理.本文选取较为复杂json格式数据,也将适用于java接口测试. JSON数据 { &q ...

  3. 使用JsonObject解析json

    第一种: [ { "0": "1", "1": "一", "id": "1", ...

  4. Android使用自带JSONObject解析JSON数据

    import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android ...

  5. 解析JSON有俩种方式:JSONObject和GSON

    JSONObject: //JSONObject解析JSON文件 private void parseJSONWithJSONObject(String json_data) { try { JSON ...

  6. json解析json字符串时候,数组必须对应jsonObjectArray,不能对应JsonObject。否则会解析错误。

    json第三方解析json字符串时候,json数组必须对应jsonObjectArray,不能对应JsonObject.->只要是[]开头的都是json数组字符串,就要用jsonArray解析 ...

  7. 使用JSONObject生成和解析json

    1. json数据类型 类型 描述 Number 数字型 String 字符串型 Boolean 布尔型 Array 数组,以"[]"括起来 Object 对象,类似于C中的结构体 ...

  8. unity解析json的两种方式

    一直比较钟情于json,用来做数据交互,堪称完美!下面简单说一下unity使用C#脚本如何解析json数据吧. 一.写解析类,借助于JsonUtility.FromJson 直接给个例子吧 1.jso ...

  9. JSON初体验(一):JsonObject解析

    在学校的呆了一段时间,马上又要回去工作了,不说了,我现在介绍一下json相关的内容 1.JSON数据格式(总的来说,json就是一个字符串) 1.整体结构 String json1 = "{ ...

随机推荐

  1. java与C++之间进行SOCKET通讯要点简要解析

    原文链接: http://blog.csdn.net/hslinux/article/details/6214594 java与C++之间进行SOCKET通讯要点简要解析 hslinux 0.篇外语 ...

  2. GPU 显存释放

    我们在使用tensorflow 的时候, 有时候会在控制台终止掉正在运行的程序,但是有时候程序已经结束了,nvidia-smi也看到没有程序了,但是GPU的内存并没有释放,那么怎么解决该问题呢? 首先 ...

  3. Excel Open Xml中CellStyleXfs,cellStyle,cellXfs之间关系的总结

    最近这几个东东打交道了几天,总算是弄明白了,综合多个帖子,现在总结如下: 在创建stylesheet时,必须创建fonts,Fills,Borders 和cellXfs(CellFormats)四个节 ...

  4. 如何使用ODBC搭配dsn链接数据库

    { OdbcConnection cn; OdbcCommand cmd; string MyString; MyString="Select * from Customers"; ...

  5. [na]IP分片抓包实验

    这两点比较重要 1.IP+ICMP+DATA = 1500字节 2.ping size指定的是data的大小. 3,可以ping大包+不分片检测mtu(分片发生在出口,如果包尺寸大于接口ip mtu, ...

  6. iphone开发之解决viewWillAppear失效

    转自:http://linuxstuding.iteye.com/blog/1224399 你可曾遇到过viewWillAppear没有被调用到的情况 产生原因是用了UINavigationContr ...

  7. Project Euler:Problem 32 Pandigital products

    We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly o ...

  8. nginx 前端调度 对后端的app的生存状态的检测

    # cat hosts.conf #app调试 upstream gl-appsrv_pools { server 10.1x0.2xx.1x0:8040; server 10.x9x.20.208: ...

  9. 最NB的发现 LINUX 下玩teamviewer 命令行设置密码

    cd /opt/teamviewer/tv_bin/ [root@666 tv_bin]# ls desktop script teamviewerd TVGuiSlave.32 xdg-utils ...

  10. spark join

    https://jaceklaskowski.gitbooks.io/mastering-apache-spark/content/spark-sql-joins.html https://acadg ...