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

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

相关推荐
虾球xz6 小时前
游戏引擎学习第246天:将 Worker 上下文移到主线程创建
c++·学习·游戏引擎
虾球xz9 小时前
游戏引擎学习第240天:将渲染器移至第三层
c++·学习·游戏引擎
林枫依依11 小时前
Unity Webgl在编辑器中报错:Cannot connect to destination host
unity·编辑器·webgl
KhalilRuan12 小时前
Unity-Shader详解-其一
unity·游戏引擎
Clank的游戏栈17 小时前
Unity多线程渲染指令队列设计与集成技术详解
windows·unity·游戏引擎
胜天半子_王二_王半仙1 天前
godot源码编译
游戏引擎·godot
Thomas_YXQ1 天前
Unity3D IK解算器技术分析
开发语言·搜索引擎·unity·全文检索·unity3d·lucene
Tandy12356_1 天前
Godot开发2D冒险游戏——第二节:主角光环整起来!
游戏引擎·godot
星火撩猿1 天前
常见游戏引擎介绍与对比
unity·ue5·游戏引擎·godot
sky_smile_Allen1 天前
[Unity]-[UI]-[Prefab] 关于Unity UGUI 的布局及组件讲解
ui·unity·游戏引擎