最近因项目需求,必须得撸撸unity了, 写点笔记,记录记录下, 在Android用Gson解析Json数据,用起来还是满愉快的, 转到Unity后,用了下SampleJson感觉太麻烦了,好的框架用爽了后,人就会变得也越懒,于是就想用其它更好用的框架,最终找到了unity5.3 以后 unity自己提供了一个JSON data的序列化与反序列化的类JsonUtility。</br>目前提供3个接口:
学Android 开发的朋友们肯定对Google的Gson不会陌生, 用起来是何等的爽, 这个Unity版的JsonUitlity应该就仿照Gson写的吧...
少bb了,it‘s time to show me the code,现在我要解析的这个json 数据如下:一个head, 一个 body且包含一个数组bookList, 还有一个page
{
"head": {
"status": 200,
"message": "ok"
},
"body": {
"bookList": [
{
"id": 1000,
"title": "呐喊",
"author": "鲁迅"
},
{
"id": 1001,
"title": "彷徨",
"author": "鲁迅"
}
]
},
"page": {
"index": 1,
"size": 500
}
}
注意 解析的对象必须要支持序列化即用[Serializable]
标记的类, 每个类的field 必须要与json的objecty一一相匹配,如: ResponseInfo的field body
对应Json对象的body
public class ResponseInfo<T>
{
public T body;
public Head head;
public Page page;
}
[Serializable]
public class Head
{
public string message;
public int status;
}
[Serializable]
public class Page
{
public int index;
public int size;
}
[Serializable]
public class BookEntity {
public int id;
public string title;
public string author;
}
[Serializable]
public class BookInfo
{
public List<BookEntity> bookList;
}
public class Test : MonoBehaviour {
string json;
void Start ()
{
//=== 构造一个将对象序列化JsonUtility.ToJson的过程 ===//
/// 初始化Head
Head head = new Head();
head.status = 200;
head.message = "ok";
/// 初始化Body
BookInfo body = new BookInfo();
List<BookEntity> bookList = new List<BookEntity>();
BookEntity entity1 = new BookEntity();
entity1.id = 1000;
entity1.title = "呐喊";
entity1.author = "鲁迅";
BookEntity entity2 = new BookEntity();
entity2.id = 1001;
entity2.title = "彷徨";
entity2.author = "鲁迅";
bookList.Add(entity1);
bookList.Add(entity2);
body.bookList = bookList;
/// 初始化 Page
Page page = new Page();
page.index = 2;
page.size = 500;
/// 构造 ReponseInfo
ResponseInfo<BookInfo> info = new ResponseInfo<BookInfo>();
info.head = head;
info.page = page;
info.body = body;
////得到序列化的json
json = JsonUtility.ToJson(responseInfo);
//=== 将json通过JsonUtility.FromJson 反序列化 ===//
ResponseInfo<BookInfo> responseInfo =JsonUtility.FromJson<ResponseInfo<BookInfo>>(json);
/// ok, that's all
}
}
怎么样,是不是比 MiniJson, SampleJson用起来方便^^
还有个接口JsonUtility.FromJsonOverwrite(json, myObject)
,暂时没用过,以后再研究....