Unity-数据持久化-JSON

一、JsonUtlity

JsonUtlity 是 Unity 自带的用于解析 Json 的公共类。它可以

  1. 将内存中对象序列化为 Json 格式的字符串

  2. 将 Json 字符串反序列化为类对象

1.在文件中存读字符串

using System.IO;

// 1.存储字符串到指定路径文件中
// 第一个参数:填写的是 存储的路径
// 第二个参数:填写的是 存储的字符串内容
// 注意:第一个参数 必须是存在的文件路径 如果没有对应文件夹 会报错
File.WriteAllText(Application.persistentDataPath + "/Test.json", "存储的json文件");
print(Application.persistentDataPath);

// 2.在指定路径文件中读取字符串
string str = File.ReadAllText(Application.persistentDataPath + "/Test.json");
print(str);

2.使用 JsonUtlity 进行序列化

​ 预备的数据结构:

[System.Serializable]
public class Student
{
    public int    age;
    public string name;

    public Student(int age, string name) {
        this.age  = age;
        this.name = name;
    }
}

public class MrTang
{
    public string name;
    public int    age;
    public bool   sex;
    public float  testF;
    public double testD;

    public int[]                      ids;
    public List<int>                  ids2;
    public Dictionary<int, string>    dic;
    public Dictionary<string, string> dic2;

    public Student       s1;
    public List<Student> s2s;

    [SerializeField] private   int privateI   = 1;
    [SerializeField] protected int protectedI = 2;
}

​ 使用方法:public static string ToJson(object obj)

// 序列化:把内存中的数据 存储到硬盘上
// 方法:
// JsonUtility.ToJson(对象)
MrTang t = new MrTang();
t.name  = "xxx";
t.age   = 18;
t.sex   = false;
t.testF = 1.4f;
t.testD = 1.4;

t.ids  = new int[] { 1, 2, 3, 4 };
t.ids2 = new List<int>() { 1, 2, 3 };
t.dic  = new Dictionary<int, string>() { { 1, "123" }, { 2, "234" } };
t.dic2 = new Dictionary<string, string>() { { "1", "123" }, { "2", "234" } };

t.s1  = null; // new Student(1, "小红");
t.s2s = new List<Student>() { new Student(2, "小明"), new Student(3, "小强") };

// Jsonutility提供了现成的方法 可以把类对象 序列化为 json字符串
string jsonStr = JsonUtility.ToJson(t);
File.WriteAllText(Application.persistentDataPath + "/MrTang.json", jsonStr);

注意:

  1. float 序列化时看起来会有一些误差
  2. 自定义类需要加上序列化特性 [System.Serializable]
  3. 想要序列化私有变量 需要加上特性 [SerializeField]
  4. JsonUtility 不支持字典
  5. JsonUtlity 存储 null 对象不会是 null 而是默认值的数据

3.使用 JsonUtlity 进行反序列化

​ 使用方法:public static T FromJson<T>(string json)

// 反序列化:把硬盘上的数据 读取到内存中
// 方法:
// JsonUtility.FromJson(字符串)
// 读取文件中的 Json字符串
jsonStr = File.ReadAllText(Application.persistentDataPath + "/MrTang.json");
// 使用Json字符串内容 转换成类对象
MrTang t2 = JsonUtility.FromJson(jsonStr, typeof(MrTang)) as MrTang;
MrTang t3 = JsonUtility.FromJson<MrTang>(jsonStr);

​ 注意:

  1. 如果 Json 中数据少了,读取到内存中类对象中时不会报错
  2. JsonUtlity 无法直接读取数据集合
  3. 文本编码格式需要是 UTF-8,不然无法加载

4.总结

  1. File 存读字符串的方法 ReadAllText 和 WriteAllText
  2. JsonUtlity 提供的序列化反序列化方法 ToJson 和 FromJson
  3. 自定义类需要加上序列化特性 [System.Serializable]
  4. 私有保护成员需要加上 [SerializeField]
  5. JsonUtlity 不支持字典
  6. JsonUtlity 不能直接将数据反序列化为数据集合
  7. Json 文档编码格式必须是 UTF-8

二、LitJson

LitJson 是一个第三方库,用于处理 Json 的序列化和反序列化

​ 它是 C# 编写的,体积小、速度快、易于使用

​ 它可以很容易的嵌入到我们的代码中,只需要将 LitJson 代码拷贝到工程中即可

1、获取 LitJson

  1. 前往 LitJson 官网:LitJSON - Home

    image-20220708222230881

  2. 通过官网前往 GitHub 获取最新版本代码

    点击此处下载最新版本:

    image-20220708222349498

  3. 将讲代码拷贝到 Unity 工程中,即可开始使用 LitJson

    代码路径在 litjson-0.18.0 -> src -> LitJson

2、使用 LitJson 进行序列化

​ 使用方法:public static string ToJson(object obj)

using LitJson;

MrTang t = new MrTang();

string jsonStr = JsonMapper.ToJson(t);
print(Application.persistentDataPath);
File.WriteAllText(Application.persistentDataPath + "/MrTang.json", jsonStr);

​ 注意:

  1. 相对 JsonUtlity 不需要加特性
  2. 不能序列化私有变量
  3. 支持字典类型。字典的键建议都是字符串。因为 Json 的特点:Json 中的键会加上双引号
  4. 需要引用 LitJson 命名空间
  5. LitJson 可以准确的保存 null 类型

3.使用 LitJson 反序列化

​ 使用方法:public static T ToObject<T>(string json)

// 方法:
// JsonMapper.ToObject(字符串)
jsonStr = File.ReadAllText(Application.persistentDataPath + "/MrTang2.json");

// JsonData 是 LitJson 提供的类对象 可以用键值对的形式去访问其中的内容
JsonData data = JsonMapper.ToObject(jsonStr);
print(data["name"]);
print(data["age"]);
// 通过泛型转换 更加的方便 建议使用这种方式
MrTang2 t2 = JsonMapper.ToObject<MrTang2>(jsonStr);

​ 注意:

  1. 类结构需要无参构造函数,否则反序列化时报错
  2. 字典虽然支持 但是键在使用为数值时会有问题 需要使用字符串类型
  3. LitJson 可以直接读取数据集合
  4. 文本编码格式需要是 UTF-8,不然无法加载

4.总结

  1. LitJson 提供的序列化反序列化方法 JsonMapper.ToJson 和 ToObject
  2. LitJson 无需加特性
  3. LitJson 不支持私有变量
  4. LitJson 支持字典序列化反序列化
  5. LitJson 可以直接将数据反序列化为数据集合
  6. LitJson 反序列化时 自定义类型需要无参构造
  7. Json 文档编码格式必须是 UTF-8

三、 JsonUtlity 和LitJson的对比

​ 1.JsonUtlity 和 LitJson 相同点:

  1. 他们都是用于 Json 的序列化反序列化
  2. Json 文档编码格式必须是 UTF-8
  3. 都是通过静态类进行方法调用

​2. JsonUtlity 和 LitJson 不同点:

  1. JsonUtlity 是 Unity 自带,LitJson 是第三方需要引用命名空间
  2. JsonUtlity 使用时自定义类需要加特性,LitJson 不需要
  3. JsonUtlity 支持私有变量(加特性),LitJson 不支持
  4. JsonUtlity 不支持字典,LitJson支持(但是键只能是字符串)
  5. JsonUtlity 不能直接将数据反序列化为数据集合(数组字典),LitJson 可以
  6. JsonUtlity 对自定义类不要求有无参构造,LitJson 需要
  7. JsonUtlity 存储空对象时会存储默认值而不是 null,LitJson 会存 null

​ 如何选择两者:根据实际需求,建议使用LitJson
​ 原因:LitJson 不用加特性,支持字典,支持直接反序列化为数据集合,存储 null 更准确

猜你喜欢

转载自blog.csdn.net/weixin_53163894/article/details/131866755