1.LitJson是什么
LitJSON - Home,Release LitJSON 0.19.0 · LitJSON/litjson · GitHub
LitJSON是一个net库,用于处理与JSON (JavaScript Object Notation)字符串之间的转换
优点:小巧、快速和易于使用
快速而精简,没有外部依赖
只有几个类,可以很容易地嵌入到您自己的代码中,或者是一个非常小的程序集,可以随代码一起发布
代码是高度可移植的,这通常使得它很容易适应新的平台
L itJson和sonUtility的区别
Unity数据持久化 之 Json序列化与反序列化-CSDN博客

导入代码包


举例的数据及实例化
注意里面的字典,JsonUtility是不能存入字典的(当然,存入私有数据需要加序列化关键词。存入null值时会有默认值,不做演示)
cs
public class Person {
public int age;
public int[] id = { 1, 2, 3 };
public Dictionary<string, int> dic = new Dictionary<string, int>();
public Children children;
public List<Teacher> teacher;
}
public class Children {
public bool isBoy;
}
public class Teacher {
public string course;
public Teacher(string c) {
course = c;
}
}
cs
Person person = new Person();
person.age = 99;
person.dic.Add("男生数量", 10);
person.dic.Add("女生数量", 9);
person.children = new Children(); // 初始化 Children 对象
person.children.isBoy = true;
person.teacher = new List<Teacher>(); // 初始化 Teacher 列表
person.teacher.Add(new Teacher("语文老师"));
person.teacher.Add(new Teacher("数学老师"));
2.序列化
引入命名空间

cs
JsonMapper.ToJson(person);
cs
// 将 JSON 数据保存到文件
string filePath = Path.Combine(Application.persistentDataPath, "example.Litjson");
File.WriteAllText(filePath, Litjson);
Debug.Log($"JSON 数据已保存至:{filePath}");
打开保存到本地的文件,可以非常完美的将字典保存了,只是编码怪怪的

不过,读字典是能读了,但是必须要string类型的键,不然你看文件中dic键值对都是双引号 ,如果你的键不是string类型吗,这在反序列化时是不被许可的
3.反序列化
索引器读
cs
//将 JSON 文件读取并返回成一个字符串
string exampleLitjson = File.ReadAllText(Application.persistentDataPath+ "/example.Litjson");
JsonData jsonData = JsonMapper.ToObject(exampleLitjson);
print(jsonData["age"]);

泛型读
cs
person = JsonMapper.ToObject<Person>(exampleLitjson);
还有一件事:如果序列化的类没有默认构造函数会报错,我没有声明有参构造顶掉无参构造,所以没报错,切记切记