Unity提供了JSON序列化相关的的工具类JsonUtility,性能比.Net的Json要好。
目前只支持MonoBehaviour,ScriptableObject,与普通Class。普通Class要标识可序列化。
同时,字段的要求与ScriptableObject的要求一致,比如不支持Dictionary的序列化。
public static string ToJson(object obj);
public static string ToJson(object obj, bool prettyPrint);
public static T FromJson(string json);
public static void FromJsonOverwrite(string json, object objectToOverwrite);
[Serializable]
public class GameData
{
public string[] Names;
public int ID;
public Dictionary<string, string> Cache;
}
void Start()
{
GameData gd = new GameData ();
gd.Names = new string[]{ "wxl", "nick" };
gd.ID = 2008;
gd.Cache = new Dictionary<string, string> ();
gd.Cache.Add ("a", "aa");
string str = JsonUtility.ToJson (gd);
Debug.Log (str);
GameData gd2 = JsonUtility.FromJson<GameData> (str);
Debug.Log (gd2.Cache == null); // Dictionary为空
Debug.Log (gd2.Names);
Debug.Log (gd2.ID);
}
https://docs.unity3d.com/560/Documentation/Manual/JSONSerialization.html