前言
Unity3D 5.3之后的版本都提供了JsonUtility类,对Json数据的序列化和反序列化原生支持。
使用心得
需要序列化或者反序列化的类前必须加上[System.Serializable]
这个Attribute
从一个最简单的栗子开始
[System.Serializable]
public class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
List<Person> persons = new List<Person>();
persons.Add(new Person("jack", 12));
persons.Add(new Person("smith", 53));
string str1 = JsonUtility.ToJson(persons);
Debug.LogError("str1:" + str1);
结果竟然是:
str1:{}
所以就有很多JsonUtility不支持List,Dictionary的解析的结论了。
那怎么解决这个问题呢,经过笔者测试,摸索出两种方式,如下文。
可以把List放到一个类中
public class Persons
{
public List<Person> allPerson = new List<Person>();
}
如上,我把List放到Persons类中
Persons persons = new Persons();
persons.allPerson.Add(new Person("jack", 12));
persons.allPerson.Add(new Person("smith", 53));
string str2 = JsonUtility.ToJson(persons);
Debug.LogError("str2:" + str2);
Persons personsDeserializ = JsonUtility.FromJson<Persons>(str2);
经过测试对Persons类进行序列化,反序列化都没有问题。而且,你发现没有,我这里Persons类,也没有加[System.Serializable]属性。
若是有直接对List,Dictionary直接操作的需求
引入以下脚本:
namespace ZGame.JsonUtilityExt
{
//支持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<Person> persons = new List<Person>();
persons.Add(new Person("jack", 12));
persons.Add(new Person("smith", 53));
string str1 = JsonUtility.ToJson(new Serialization<Person>(persons));
Debug.LogError("str1:" + str1);
List<Person> personsDeserializ = JsonUtility.FromJson<Serialization<Person>>(str1).ToList();