using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; using System.IO; /// /// 使用类型 /// public enum JsonType { /// /// 第三方 /// LitJson, /// /// 系统自带 /// JsonUtility, } /// /// Json数据处理 类 用于处理Json数据 /// Unity有自带的json处理类JsonUtility /// 不支持字典 /// 自定义类需要加特性[System.Serializable] /// private protected 类需要序列化 需要加特性[SerializeField] /// 不能直接读取数组数据 /// 我们常用LitJson /// 不支持私有变量 /// JsonData可以用来获取 字段内容 /// 字典需要使用 键string类型 /// 自定义类需要使用 无参构造函数 /// 文本编码格式UTF-8 /// public class JsonManager : BaseManager { private JsonManager() { } /// /// 保存数据 PC端 /// /// 需要存储的数据对象 /// 存储为的文件名 /// 存储方式,默认LitJson public void SaveData(object data ,string fileName,JsonType type = JsonType.LitJson) { //存储路径 string path = Application.persistentDataPath + "/" + fileName + ".json"; //序列化 得到json字符串 string json = ""; switch (type) { case JsonType.LitJson: json = JsonMapper.ToJson(data); break; case JsonType.JsonUtility: json = JsonUtility.ToJson(data); break; } //把json字符串保存成文件 File.WriteAllText(path, json); } /// /// 读取数据 PC端 /// /// 类型 /// /// public T LoadData(string fileName,JsonType type = JsonType.LitJson) where T : new() { //路径 string path = Application.streamingAssetsPath + "/" + fileName + ".json"; if (!File.Exists(path)) { path = Application.persistentDataPath + "/" + fileName + ".json"; } if (!File.Exists(path)) { return new T(); } //获取json字符串 string jsonStr = File.ReadAllText(path); // T data = new T(); //反序列 switch (type) { case JsonType.LitJson: data = JsonMapper.ToObject(jsonStr); break; case JsonType.JsonUtility: data = JsonUtility.FromJson(jsonStr); break; } return data; } }