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

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

相关推荐
IMPYLH31 分钟前
Lua 的 xpcall 函数
开发语言·笔记·后端·游戏引擎·lua
AI视觉网奇15 小时前
虚幻引擎 metahuman
游戏引擎·虚幻
技术探讨者21 小时前
Unity 框架:从核心构成到实践应用的全面解析
unity·游戏引擎
牛掰是怎么形成的21 小时前
Unity Legacy动画与骨骼动画的本质区别
unity·游戏引擎
weixin_4583609121 小时前
Unity使用Cursor Editor
unity
萘柰奈21 小时前
Unity学习--2D动画--[序列帧动画]2D序列帧动画
学习·unity·游戏引擎
EQ-雪梨蛋花汤21 小时前
【Unity笔记】Unity 模型渲染优化:从 Batching 到 GI 设置的完整指南
笔记·unity·游戏引擎
花花_121 小时前
一步封神:Unity环境搭建终极全宇宙级攻略(Win/Mac/云)
macos·unity·游戏引擎
Unity打怪升级21 小时前
【Unity精品源码】Ultimate Character Controller:高级角色控制器完整解决方案
游戏·unity·ue5·游戏引擎·godot·游戏程序·cocos2d