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();