Unity-data persistence-JSON

1. JsonUtlity

JsonUtlity is a public class that comes with Unity for parsing Json. it can

  1. Serialize an object in memory to a string in Json format

  2. Deserialize Json string to class object

1. Store and read strings in files

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. Use JsonUtlity for serialization

​ Prepared data structure:

[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;
}

​ How to use: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);

Notice:

  1. There seems to be some errors when float serialization
  2. Custom classes need to add serialization features [System.Serializable]
  3. To serialize private variables, you need to add the feature [SerializeField]
  4. JsonUtility does not support dictionaries
  5. JsonUtlity stores null object will not be null but default value data

3. Use JsonUtlity for deserialization

​ How to use: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);

Note:

  1. If there is less data in Json, no error will be reported when reading it into the class object in memory
  2. JsonUtlity cannot directly read the data collection
  3. The text encoding format needs to be UTF-8, otherwise it cannot be loaded

4. Summary

  1. The methods ReadAllText and WriteAllText for storing and reading strings in File
  2. The serialization and deserialization methods ToJson and FromJson provided by JsonUtlity
  3. Custom classes need to add serialization features [System.Serializable]
  4. Private protection members need to add [SerializeField]
  5. JsonUtlity does not support dictionaries
  6. JsonUtlity cannot directly deserialize data into a data collection
  7. Json document encoding format must be UTF-8

2. LitJson

LitJson is a third-party library for serialization and deserialization of Json

​ It is written in C#, small size, fast and easy to use

​ It can be easily embedded into our code, just copy the LitJson code into the project

1. Get LitJson

  1. Go to LitJson official website: LitJSON - Home

    image-20220708222230881

  2. Go to GitHub to get the latest version code through the official website

    Click here to download the latest version:

    image-20220708222349498

  3. Copy the code into  the Unity  project and start using LitJson

    The code path is in litjson-0.18.0  -> src  -> LitJson

2. Use LitJson for serialization

​ How to use: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);

Note:

  1. Relative to JsonUtlity, no need to add features
  2. Cannot serialize private variable
  3. Dictionary type is supported. The key suggestions of the dictionary are all strings. Because of the characteristics of Json: the keys in Json will be double quoted
  4. Need to reference the LitJson namespace
  5. LitJson can accurately save the null type

3. Use LitJson to deserialize

​ How to use: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);

Note:

  1. The class structure requires a no-argument constructor, otherwise an error will be reported for deserialization
  2. Although the dictionary supports it, there will be problems when the key is used as a value, and the string type needs to be used
  3. LitJson can directly read data collections
  4. The text encoding format needs to be UTF-8, otherwise it cannot be loaded

4. Summary

  1. The serialization and deserialization methods provided by LitJson JsonMapper.ToJson and ToObject
  2. LitJson does not need to add features
  3. LitJson does not support private variables
  4. LitJson supports dictionary serialization and deserialization
  5. LitJson can directly deserialize data into a data collection
  6. When LitJson deserializes, the custom type needs no parameter construction
  7. Json document encoding format must be UTF-8

3. Comparison of JsonUtlity and LitJson

1. JsonUtlity is the same as LitJson:

  1. They are all used for serialization and deserialization of Json
  2. Json document encoding format must be UTF-8
  3. Method calls are made through static classes

​2. Differences between JsonUtlity and LitJson:

  1. JsonUtlity comes with Unity, and LitJson is a third-party namespace that needs to be referenced
  2. Custom classes need to add features when using JsonUtlity, LitJson does not
  3. JsonUtlity supports private variables (plus features), LitJson does not
  4. JsonUtlity does not support dictionaries, LitJson does (but keys can only be strings)
  5. JsonUtlity cannot directly deserialize data into a data collection (array dictionary), LitJson can
  6. JsonUtlity does not require no-argument construction for custom classes, but LitJson does
  7. When JsonUtlity stores an empty object, it will store the default value instead of null, and LitJson will store null

How to choose the two: According to actual needs, it is recommended to use LitJson
Reason: LitJson does not need to add features, supports dictionaries, supports direct deserialization into data sets, and stores null more accurately

Guess you like

Origin blog.csdn.net/weixin_53163894/article/details/131866755