Unity数据持久化 之 LitJson序列化与反序列化

语法规则可以看这篇文章:Unity数据持久化 之 Json 语法速通-CSDN博客

1.LitJson是什么

LitJSON - HomeRelease 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);

还有一件事:如果序列化的类没有默认构造函数会报错,我没有声明有参构造顶掉无参构造,所以没报错,切记切记

相关推荐
微三云生态系统架构师-彭丹10 小时前
任务卷轴积分系统架构设计:从任务状态机到合规风控的完整实现
unity·系统架构·游戏引擎
XR技术研习社12 小时前
从 PICO 文档看未来短期内的 Unity 版本选择
unity·游戏引擎·xr·vr
玖玥拾14 小时前
Unity 热更新(一)
unity·游戏引擎
软件黑马王子14 小时前
1.non-MonoBehaviour 单例模式泛型基类
unity·前端框架·c#
KhalilRuan1 天前
Unity性能优化
unity·性能优化·游戏引擎
ellis19701 天前
u3d IMGUI[二] 编辑器扩展
unity
五仁烧饼2 天前
Unity性能优化系列内存篇 - 移动端内存优化
unity·性能优化·游戏引擎
WiChP3 天前
【V0.1B15】从零开始的2D游戏引擎开发之路
游戏引擎
zhchyun20084 天前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(06)
ui·unity·游戏引擎
Behaviour5 天前
Unity游戏HybridCLR 热更新接入实战
游戏·unity·游戏引擎