在Unity中使用 JsonFx 插件筆記(提示:如下在 Unity3D v5.4.0 版本 Win 平臺下測試成功)android
1 using Pathfinding.Serialization.JsonFx;
1 public class Person 2 { 3 public string name; 4 public int age; 5 6 public Person(): this("", 1) { 7 8 } 9 10 public Person(string _name, int _age) { 11 name = _name; 12 age = _age; 13 } 14 15 }//public class Person 16 17 #endregion 18 19 public class C_9_9 : MonoBehaviour 20 { 21 22 // Use this for initialization 23 void Start () { 24 25 Person john = new Person("John", 19); 26 // 將對象序列化成Json字符串 27 string Json_Text = JsonWriter.Serialize(john); 28 Debug.Log(Json_Text); 29 // 將字符串反序列化成對象 30 // john = JsonReader.Deserialize(Json_Text) as Person; // 提示,使用這種方式沒辦法正確反序列化成功 john 對象 31 john = JsonReader.Deserialize<Person>(Json_Text); // 提示,使用這種方式要求 Person 類必須要有一個默認構造函數 32 Debug.Log("john.name = " + john.name); 33 Debug.Log("john.age = " + john.age); 34 35 } 36 37 }
1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.UI; 4 using Pathfinding.Serialization.JsonFx; 5 using System.IO; 6 7 public class Person 8 { 9 public string name; 10 public int age; 11 12 public Person(): this("", 1) { 13 14 } 15 16 public Person(string _name, int _age) { 17 name = _name; 18 age = _age; 19 } 20 21 }//public class Person 22 23 public class C_9_9 : MonoBehaviour 24 { 25 26 // Use this for initialization 27 void Start () { 28 29 Person john = new Person("John", 19); 30 // 將對象序列化成Json字符串 31 string Json_Text = JsonWriter.Serialize(john); 32 Debug.Log(Json_Text); 33 // 將字符串反序列化成對象 34 // john = JsonReader.Deserialize(Json_Text) as Person; // 提示,使用這種方式沒辦法正確反序列化成功 john 對象 35 john = JsonReader.Deserialize<Person>(Json_Text); // 提示,使用這種方式要求 Person 類必須要有一個默認構造函數 36 Debug.Log("john.name = " + john.name); 37 Debug.Log("john.age = " + john.age); 38 39 // 這邊將剛纔序列化後的字符串保存起來 40 string dataPath = GetDataPath() + "/jsonfx_test/person_john.txt"; 41 File.WriteAllText(dataPath, Json_Text); 42 43 } 44 45 // 取得可讀寫路徑 46 public static string GetDataPath() { 47 if (RuntimePlatform.IPhonePlayer == Application.platform) { 48 // iPhone 路徑 49 string path = Application.dataPath.Substring(0, Application.dataPath.Length - 5); 50 path = path.Substring(0, path.LastIndexOf('/')); 51 return path + "/Documents"; 52 } else if (RuntimePlatform.Android == Application.platform) { 53 // 安卓路徑 54 //return Application.persistentDataPath + "/"; 55 return Application.persistentDataPath; 56 } else { 57 // 其餘路徑 58 return Application.dataPath; 59 } 60 } 61 62 }