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

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

相关推荐
心疼你的一切16 小时前
使用Unity引擎开发Rokid主机应用的模型交互操作
游戏·ui·unity·c#·游戏引擎·交互
淡海水17 小时前
【URP】Unity[内置Shader]光照着色器Lit
unity·游戏引擎·shader·urp·着色器·lit
爱吃小胖橘18 小时前
Lua语法(2)
开发语言·unity·lua
心疼你的一切1 天前
使用Unity引擎开发Rokid主机应用的全面配置交互操作
学习·游戏·unity·c#·游戏引擎·交互
qq_428639612 天前
虚幻基础:角色受击
游戏引擎·虚幻
ellis19702 天前
LuaC API知识点汇总
unity·lua
maki0772 天前
虚幻版Pico大空间VR入门教程 05 —— 原点坐标和项目优化技巧整理
android·游戏引擎·vr·虚幻·pico·htc vive·大空间
一线灵2 天前
跨平台游戏引擎 Axmol-2.9.0 发布
游戏引擎
maki0772 天前
VR大空间资料 01 —— 常用VR框架对比
android·ue5·游戏引擎·vr·虚幻·pico
maki0773 天前
VR大空间资料 02 —— 常用Body IK对比
android·游戏引擎·vr·虚幻·pico·ik