一、使用注意事项:
- 被转换的对象必须是可被序列化的,需要标记 [System.Serializable] 属性;
- JsonUtility.FromJson 方法只能接受 json 对象,如果是 json 数组会提示错误: JSON must represent an object type。
二、要解析的Json数据:
{
"stat": 1,
"status": 1,
"msg": "\u64cd\u4f5c\u6210\u529f",
"data": {
"ARM": 1,
"model": [{
"mname": "1x1",
"name": "road",
"pos": {
"x": -155,
"y": 140,
"direction": 90
},
"size": [40, 40]
}, {
"mname": "3x3",
"name": "park",
"pos": {
"x": -35,
"y": 60,
"direction": 90
},
"size": [119, 119]
}, {
"mname": "游乐园",
"name": "游乐园",
"pos": {
"x": 240,
"y": 180,
"direction": 90
},
"size": [111, 111]
}]
}
}
三、解析方法(类中需是字段,不能是属性):
[Serializable]
public class Pos
{
public int x;
public int y;
public int direction;
}
[Serializable]
public class Model
{
public string mname;
public string name;
public Pos pos;
public List<int> size;
}
[Serializable]
public class Data
{
public int ARM;
public List<Model> model;
}
[Serializable]
public class JsonObject
{
public int stat;
public int status;
public string msg;
public Data data;
}
private JsonObject jsonObject;
private void RecvGetMsg(string json)//通过Json初始化obj的值
{
//jsonObject = JsonUtility.FromJson<JsonObject>(json);//方法一
JsonUtility.FromJsonOverwrite(json, jsonObject);//方法二
Debug.Log(json+jsonObject.stat + "," + jsonObject.status+"," +jsonObject.data.ARM);
}