Unity作为客户端要与服务端通信,最为简单通信协议就是使用Json格式。本文简单讲述Unity使用JsonFx进行Json(反)序列。
序列和反序列是一个互为逆反的过程。反序列化可以帮助我们将已从文本中读取的一个字符串(确切是符合Json的字符串)解析成一种类型的数据实例,并且加载到内存中,直到我们摧毁它或停止应用程序。一旦我们在 unity 编辑器 (或关闭我们build生成中的窗口)关闭播放play模式,该数据就丢失了。而序列化是为了将其存储到文件系统中,不仅我们可以脱机编辑,而且当我们再次加载它,可以查看更改反映在我们的应用程序。
JsonFx是一个JSON (反)序列的插件,点此下载
容器其实是你想通过json字符串解析出来的类,他包含了若干个字段数据,例如Sandwich类
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class Sandwich{
public string name;
public string bread;
public float price;
public List<string> ingredients = new List<string>();
}
在Sanwich.cs中,共有name, bread, price, ingredients等字段,只是注意字段都是public的,这一点很重要! 此外,[System.Serializable] 能为我们做两件事: 它允许 JsonFx 要序列化的字段,并y的inspector面板上,将这些字段。
那应该怎么样的json字符串才能解析出来呢?请看下一章节。
反序列json字符串其实也非常简单,只需要遵循以下规则:
例如,上述的Sanwich类的一个可行的反序列json字符串为:
string sandwich_json = "{\"name\":\"haqi\", \"bread\":\"tudo usi\", \"price\":1.45, \"ingredients\":[\"sala\",\"beef \",\"cheese\",\"whatever\"]}";
栗子即是上述Sandwich由反序列,然后序列化,最后保存的完整代码:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using JsonFx.Json;
using System.IO;
// Sanwich类
[System.Serializable]
public class Sandwich{
public string name;
public string bread;
public float price;
public List<string> ingredients = new List<string>();
}
public class Test : MonoBehaviour {
void Start(){
//准备反序列化json字符串
string sandwich_json = "{\"name\":\"haqi\", \"bread\":\"tudousi\", \"price\":1.45, \"ingredients\":[\"sala\",\"beef\",\"cheese\",\"whatever\"]}";
// 反序列化,下个函数
Sandwich sw = Deserialize (sandwich_json);
// 修改属性
sw.bread = "this_bread_is_changed";
// 序列化并且保存,下下个函数
SerializeAndSave (sw);
}
// 反序列化
Sandwich Deserialize(string sw_json){
// 使用JsonFx反序列功能
Sandwich sw = JsonReader.Deserialize<Sandwich> (sw_json);
Debug.Log ("name:" + sw.name);
Debug.Log ("bread:" + sw.bread);
Debug.Log ("price:" + sw.price.ToString());
Debug.Log ("first ingredients:" + sw.ingredients[0]);
return sw;
}
void SerializeAndSave(Sandwich sw) {
// 使用JsonFx序列化功能
string data = JsonWriter.Serialize(sw);
//持久化
var streamWriter = new StreamWriter(Path.Combine(Application.persistentDataPath, "serialize_sandwich.json"));
streamWriter.Write(data);
streamWriter.Close();
}
}
最后修改了Sandwich实例,并且持久化到“serialize_sandwich.json”内容为:
{"name":"haqi","bread":"this_bread_is_changed","price":1.45,"ingredients":["sala","beef","cheese","whatever"]}
同时也欢迎大家移步我的github下载代码。