1. JsonUtlity
JsonUtlity is a public class that comes with Unity for parsing Json. it can
-
Serialize an object in memory to a string in Json format
-
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:
- There seems to be some errors when float serialization
- Custom classes need to add serialization features [System.Serializable]
- To serialize private variables, you need to add the feature [SerializeField]
- JsonUtility does not support dictionaries
- 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:
- If there is less data in Json, no error will be reported when reading it into the class object in memory
- JsonUtlity cannot directly read the data collection
- The text encoding format needs to be UTF-8, otherwise it cannot be loaded
4. Summary
- The methods ReadAllText and WriteAllText for storing and reading strings in File
- The serialization and deserialization methods ToJson and FromJson provided by JsonUtlity
- Custom classes need to add serialization features [System.Serializable]
- Private protection members need to add [SerializeField]
- JsonUtlity does not support dictionaries
- JsonUtlity cannot directly deserialize data into a data collection
- 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
-
Go to LitJson official website: LitJSON - Home
-
Go to GitHub to get the latest version code through the official website
Click here to download the latest version:
-
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:
- Relative to JsonUtlity, no need to add features
- Cannot serialize private variable
- 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
- Need to reference the LitJson namespace
- 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:
- The class structure requires a no-argument constructor, otherwise an error will be reported for deserialization
- 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
- LitJson can directly read data collections
- The text encoding format needs to be UTF-8, otherwise it cannot be loaded
4. Summary
- The serialization and deserialization methods provided by LitJson JsonMapper.ToJson and ToObject
- LitJson does not need to add features
- LitJson does not support private variables
- LitJson supports dictionary serialization and deserialization
- LitJson can directly deserialize data into a data collection
- When LitJson deserializes, the custom type needs no parameter construction
- Json document encoding format must be UTF-8
3. Comparison of JsonUtlity and LitJson
1. JsonUtlity is the same as LitJson:
- They are all used for serialization and deserialization of Json
- Json document encoding format must be UTF-8
- Method calls are made through static classes
2. Differences between JsonUtlity and LitJson:
- JsonUtlity comes with Unity, and LitJson is a third-party namespace that needs to be referenced
- Custom classes need to add features when using JsonUtlity, LitJson does not
- JsonUtlity supports private variables (plus features), LitJson does not
- JsonUtlity does not support dictionaries, LitJson does (but keys can only be strings)
- JsonUtlity cannot directly deserialize data into a data collection (array dictionary), LitJson can
- JsonUtlity does not require no-argument construction for custom classes, but LitJson does
- 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