Unity Json 之三
今天在網上看到一個simplejson,直接調用這兩個API就可以了,簡單易用
string jsonstr = SimpleJson.SimpleJson.SerializeObject(json);
Debug.LogError(jsonstr);
TestJson test = SimpleJson.SimpleJson.DeserializeObject<TestJson>(jsonstr);
做了測試和JsonUtility.ToJson(json);幾乎是一樣的,但是JsonUtility.ToJson(json); 需要在每個類上加上[System.Serializable] 特性標簽 ,並且只能用字段,不能用屬性 ,都可以滿足我們日常需求
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class TestJson { [SerializeField] //經測試,加不加都可以 public string Name; [SerializeField] public Student[] stud; } [System.Serializable] public class Student { [SerializeField]public string School; [SerializeField] public Gender gender; } [System.Serializable] public class Gender { [SerializeField] public int age; [SerializeField] public List<int> list; } public class TestSimpliJson : MonoBehaviour { // Use this for initialization voidStart() { Tess(); } void Tess() { TestJson json = new TestJson(); json.Name = "飛天小豬"; json.stud = new Student[4]; for (int i = 0; i < json.stud.Length; i++) { json.stud[i] = new Student(); json.stud[i].School = "飛天小豬" + i; json.stud[i].gender = new Gender(); json.stud[i].gender.age = i; json.stud[i].gender.list = new List<int>(); for (int j = 0; j < i * i; j++) { json.stud[i].gender.list.Add(j); } } string jsonstr = SimpleJson.SimpleJson.SerializeObject(json); Debug.LogError(jsonstr); TestJson test = SimpleJson.SimpleJson.DeserializeObject<TestJson>(jsonstr); string strJson = JsonUtility.ToJson(json); Debug.LogError(strJson); } }
兩種方式,輸出如下
{"Name":"飛天小豬","stud":[{"School":"飛天小豬0","gender":{"age":0,"list":[]}},{"School":"飛天小豬1","gender":{"age":1,"list":[0]}},{"School":"飛天小豬2","gender":{"age":2,"list":[0,1,2,3]}},{"School":"飛天小豬3","gender":{"age":3,"list":[0,1,2,3,4,5,6,7,8]}}]}
不過如果不給list賦值,稍微有點不一樣的地方
{"Name":"飛天小豬","stud":[{"School":"飛天小豬0","gender":{"age":0,"list":null}},{"School":"飛天小豬1","gender":{"age":1,"list":null}},{"School":"飛天小豬2","gender":{"age":2,"list":null}},{"School":"飛天小豬3","gender":{"age":3,"list":null}}]}
{"Name":"飛天小豬","stud":[{"School":"飛天小豬0","gender":{"age":0,"list":[]}},{"School":"飛天小豬1","gender":{"age":1,"list":[]}},{"School":"飛天小豬2","gender":{"age":2,"list":[]}},{"School":"飛天小豬3","gender":{"age":3,"list":[]}}]}
Unity Json 之三