文章目录
JsonUtlity 是 Unity 自带的用于解析 Json 的公共类。它可以
- 一、在文件中存读字符串
- 二、使用 JsonUtlity 进行序列化
- 三、使用 JsonUtlity 进行反序列化
- 四、总结
-
将内存中对象序列化为 Json 格式的字符串
-
将 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 ids2;
public Dictionary dic;
public Dictionary dic2;
public Student s1;
public List 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() { 1, 2, 3 };
t.dic = new Dictionary() { { 1, "123" }, { 2, "234" } };
t.dic2 = new Dictionary() { { "1", "123" }, { "2", "234" } };
t.s1 = null; // new Student(1, "小红");
t.s2s = new List() { new Student(2, "小明"), new Student(3, "小强") };
// Jsonutility提供了现成的方法 可以把类对象 序列化为 json字符串
string jsonStr = JsonUtility.ToJson(t);
File.WriteAllText(Application.persistentDataPath + "/MrTang.json", jsonStr);
注意:
- float 序列化时看起来会有一些误差
- 自定义类需要加上序列化特性 [System.Serializable]
- 想要序列化私有变量 需要加上特性 [SerializeField]
- JsonUtility 不支持字典
- JsonUtlity 存储 null 对象不会是 null 而是默认值的数据
使用方法:public static T FromJson(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(jsonStr);
注意:
- 如果 Json 中数据少了,读取到内存中类对象中时不会报错
- JsonUtlity 无法直接读取数据集合
- 文本编码格式需要是 UTF-8,不然无法加载
- File 存读字符串的方法 ReadAllText 和 WriteAllText
- JsonUtlity 提供的序列化反序列化方法 ToJson 和 FromJson
- 自定义类需要加上序列化特性 [System.Serializable]
- 私有保护成员需要加上 [SerializeField]
- JsonUtlity 不支持字典
- JsonUtlity 不能直接将数据反序列化为数据集合
- Json 文档编码格式必须是 UTF-8