Unity中JsonUtility對List和Dictionary的序列化
阿新 • • 發佈:2019-01-27
Unity5.3從開始追加的JsonUtility,但是對於List 和Dictionary不能被直接序列化儲存
例如:
資料模型
實際使用using UnityEngine; using System; using System.Collections.Generic; [Serializable] public class Enemy { [SerializeField] string name; [SerializeField] List<string> skills; public Enemy(string name, List<string> skills) { this.name = name; this.skills = skills; } }
List<Enemy> enemies = new List<Enemy>();
enemies.Add(new Enemy("怪物1", new List<string>() { "攻擊" }));
enemies.Add(new Enemy("怪物2", new List<string>() { "攻擊", "恢復" }));
Debug.Log(JsonUtility.ToJson(enemies));
輸出為:{}
輸出是沒有任何的json字串。
在unity的官方網站,ISerializationCallbackReceiver
// Serialization.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System; // List<T> [Serializable] public class Serialization<T> { [SerializeField] List<T> target; public List<T> ToList() { return target; } public Serialization(List<T> target) { this.target = target; } } // Dictionary<TKey, TValue> [Serializable] public class Serialization<TKey, TValue> : ISerializationCallbackReceiver { [SerializeField] List<TKey> keys; [SerializeField] List<TValue> values; Dictionary<TKey, TValue> target; public Dictionary<TKey, TValue> ToDictionary() { return target; } public Serialization(Dictionary<TKey, TValue> target) { this.target = target; } public void OnBeforeSerialize() { keys = new List<TKey>(target.Keys); values = new List<TValue>(target.Values); } public void OnAfterDeserialize() { var count = Math.Min(keys.Count, values.Count); target = new Dictionary<TKey, TValue>(count); for (var i = 0; i < count; ++i) { target.Add(keys[i], values[i]); } } }
使用
// List<T> -> Json ( 例 : List<Enemy> )
string str = JsonUtility.ToJson(new Serialization<Enemy>(enemies)); // 輸出 : {"target":[{"name":"怪物1,"skills":["攻擊"]},{"name":"怪物2","skills":["攻擊","恢復"]}]}
// Json-> List<T>
List<Enemy> enemies = JsonUtility.FromJson<Serialization<Enemy>>(str).ToList();
// Dictionary<TKey,TValue> -> Json( 例 : Dictionary<int, Enemy> )
string str = JsonUtility.ToJson(new Serialization<int, Enemy>(enemies)); // 輸出 : {"keys":[1000,2000],"values":[{"name":"怪物1","skills":["攻擊"]},{"name":"怪物2","skills":["攻擊","恢復"]}]}
// Json -> Dictionary<TKey,TValue>
Dictionary<int, Enemy> enemies = JsonUtility.FromJson<Serialization<int, Enemy>>(str).ToDictionary();