Unity 持久化储存

1
2
3
4
5
6
7
8
9
### LitJosn

`using LitJson` 引入命名空间

#### 序列化

```csharp
string Json = JsonMapper.ToJson(lineList);
File.WriteAllText(Application.persistentDataPath + "/save.json", Json);

lineList 是要序列化的对象

反序列化

1
2
string data = File.ReadAllText(Application.persistentDataPath + "/save.json");
List<List<int>> Data = JsonMapper.ToObject<List<List<int>>>(data);

lineList 是什么类型就用什么类型接收,例如这里用 List<List<int>> 接收

JsonUnity

1
2
3
4
5
6
7
8
9
10
11
12
13
// File.WriteAllText写出文件、File.ReadAllText读入文件、JsonUtility.ToJson(obj)、JsonUtility.FromJson<T>(json)
private void Save()
{
StartData startData = new StartData();
string json = JsonUtility.ToJson(startData); // 将StartData对象转化为json字符串
File.WriteAllText(Application.persistentDataPath + "/StartData.json", json); // 将json字符串写入文件中
}

private void Read()
{
string json = File.ReadAllText(Application.persistentDataPath + "/StartData.json"); // 读取文件中的json字符串
StartData startData = JsonUtility.FromJson<StartData>(json); // 将json字符串转化为StartData对象
}

注意

  1. float 序列化可能存在微小误差(不影响使用)
  2. 自定义类需添加序列化标记 [System.Serializable]
  3. 序列化私有变量需添加 [SerializeField]
  4. 不支持字典类型
  5. 存储的 null 对象会被转换为默认类型值