2022-07-08 Unity Json1——JsonUtlity


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

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

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

一、在文件中存读字符串

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

二、使用 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 而是默认值的数据

三、使用 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,不然无法加载

四、总结

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

猜你喜欢

转载自blog.csdn.net/zheliku/article/details/125687182