【Unity数据持久化_Json】(四)LitJson是什么?使用LitJson序列化、反序列化

一、LitJson是什么?

LitJson是一个第三方库,用于处理Json的序列化和反序列化
LitJson是用C#编写的,它体积小、速度快、易于使用
它可以很容易的嵌入代码中
只需要将LitJson代码拷贝到工程中即可

二、获取LitJson

1.前往LitJson官网
2.通过官网前往GitHub获取最新代码版本
3.解压后,进入src目录,将LitJson目录拷贝到Unity工程即可
在这里插入图片描述
只保留LitJson中的C#脚本文件,其他的都可以删除
在这里插入图片描述

三、使用LitJson进行序列化

API:JsonMapper.ToJson(对象);

注意
1.需要引用命名空间LitJson
2.相对JsonUtlity 不需要加特性
3.不能序列化私有化变量
4.支持字典

using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
//准备数据结构类
public class PlayerInfo3
{
    
    
    public string name;
    public int age;
    public bool sex;
    public float speed;
    public int[] ids;
    public List<int> ids2;
    public Dictionary<int, string> dic;
    public Item3 item1;
    public List<Item3> item2;
    private int testPrivate = 1;
    protected int testProtected = 2;
}
public class Item3
{
    
    
    public int id;
    public int num;
    public Item3(int id, int num)
    {
    
    
        this.id = id;
        this.num = num;
    }
}
public class Lesson2 : MonoBehaviour
{
    
    
    void Start()
    {
    
    
        //声明对象 并初始化数据
        PlayerInfo3 p = new PlayerInfo3();
        p.name = "假面骑士1号";
        p.age = 24;
        p.sex = true;
        p.speed = 56.7f;
        p.ids = new int[] {
    
     1, 2, 3 };
        p.ids2 = new List<int>() {
    
     4, 5, 6 };
        p.dic = new Dictionary<int, string>() {
    
     {
    
     1, "啊" }, {
    
     2, "哈" } };
        p.item1 = new Item3(1, 10);
        p.item2 = new List<Item3>() {
    
     new Item3(2, 4), new Item3(3, 99) };
        //序列化此对象
        //(把类对象序列化为了Json字符串)
        string jsonStr = JsonMapper.ToJson(p);
        //把序列化后的字符串存到本地
        File.WriteAllText(Application.persistentDataPath + "/PlayerInfoJson3.json",  jsonStr);
    }
}

在这里插入图片描述
序列化之后的字符串看起来有些奇怪
不用管,反序列化时会恢复正常
四、使用LitJson进行反序列化

API:JsonMapper.ToObject(字符串);

注意
1.类结构需要无参构造函数,否则反序列化时会报错
2.虽然支持字典,但键在使用为数值时会有问题,需要使用字符串类型
    因为在序列化时,就算键是int,也会被强制加""
    在反序列化时,int型的键去读取Json文件中string型的值,就会报错

根据"注意"把准备好的数据结构类进行改造,再反序列化

        string jsonStr = File.ReadAllText(Application.persistentDataPath +  "/PlayerInfoJson3.json");
        //重载一: 返回一个JsonData (很少用)
        //  JsonData是LitJson提供的类对象,可以用于键值对的形式访问其中变量
        JsonData data = JsonMapper.ToObject(jsonStr);
        //  键就是变量名
        print(data["name"]);

        //重载二:泛型
        PlayerInfo3 p3 = JsonMapper.ToObject<PlayerInfo3>(jsonStr);

五、注意事项

1.相比Jsonutility,LitJson可以直接读取数据结合
例:继续尝试去读取下图
在这里插入图片描述

        string jsonStr = File.ReadAllText(Application.streamingAssetsPath +  "/RoleInfo.json");
        RoleInfo2[] arr = JsonMapper.ToObject<RoleInfo2[]>(jsonStr);
        //也可以存成List
        List<RoleInfo2> list = JsonMapper.ToObject<List<RoleInfo2>>(jsonStr);

2.同Jsonutility,文本编码格式需要是UTF-8,否则无法加载

猜你喜欢

转载自blog.csdn.net/SEA_0825/article/details/127254073