Unity自帶的Json解析工具類JsonUtility居然沒有API用於解析集合類型,也太鬼扯了吧。
- https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity
- http://www.boxheadproductions.com.au/deserializing-top-level-arrays-in-json-with-unity/
下面是一個簡單的例子:
Student.json:是一個數組。
[ { "id": "1", "name": "A" }, { "id": "2", "name": "B" } ]
解析Json:
// 解析Json的方法 public void ParseItemJson(string jsonStr) { // 將Json中的數組用一個list包裹起來,變成一個Wrapper對象 jsonStr = "{ \"list\": " + jsonStr + "}"; Response<Student> studentList = JsonUtility.FromJson<Response<Student>>(jsonStr); foreach (Student item in studentList.list) { Debug.Log(item.id); } } // Json解析為該對象 public class Response<T> { public List<T> list; } [Serializable] public class Student { public int id; public string name; }
坑點:
- Student類中的屬性要與Json中的屬性一致,大小寫敏感!否則能解析為對象,但對象的屬性為默認值(int默認0,string默認null等)。
- Student類要標記為[Serializable],Response類可以不用標記。
- Json前面拼接的 \"list\"必須要和Response中的list屬性一致,大小寫敏感!
根據上面的第三個坑點,對於這種包含數組/集合的數據,后台最好不是直接返回一個數組,而是返回一個對象,對象內部包含一個數組。數據格式如下:
{
"list": [
{
"id": "1",
"name": "A"
},
{
"id": "2",
"name": "B"
}
]
}
JsonUtility用着實在蛋疼,還是換回熟悉的Newtonsoft.json吧。
- https://www.newtonsoft.com/json
- http://www.cnblogs.com/guxin/p/csharp-parse-json-by-newtonsoft-json-net.html
由於Unity使用的.Net Framwork版本太低,直接Nuget下載的Newtonsoft.json是不能安裝的。報錯如下圖:
解決辦法: