存入和读取JSON工具
目录
存入和读取JSON工具
读取本地Json文件
1、unity自带方法
类名:JsonUtility
序列化:ToJson()
反序列化:FromJson<>()
用于接收的JSON实体类需要声明
[Serializable]
序列化实体类中的成员变量要是字段而不是属性{get;set;}
处理数组的话,外面再包裹一层对象
2、Newtonsoft插件
类名:JsonConvert
序列化:SerializeObject()
反序列化:DeserializeObject<>()
3、LitJson插件
类名:JsonMapper
序列化:ToJson()
反序列化:ToObject<>()
实体类可以不用声明
[Serializable]
实体类中的成员变量可以是字段也可以是属性{get;set;}
可以直接处理数组
读取本地Json文件
(1)json文件放在Resources文件夹中
1、使用Resources.Load<TextAsset>方法读取
string jsonFilePath = "JsonFileName"; // 不带扩展名
TextAsset jsonTextAsset = Resources.Load<TextAsset>(jsonFilePath);
string jsonFileContent = jsonTextAsset.text;
(2)json文件放到StreamingAssets文件夹
1、使用Application.streamingAssetsPath获取路径:
string jsonFilePath = Path.Combine(Application.streamingAssetsPath, "example.json");
2、使用Application.dataPath获取路径
string jsonFilePath = Path.Combine(Application.dataPath,"StreamingAssets/example.json.bytes");using (StreamReader reader = new StreamReader(jsonFilePath))
{
string jsonContent = reader.ReadToEnd();
// 在这里可以使用jsonContent进行进一步的处理‘
Debug.Log("JSON内容:" + jsonContent);
}
(3)json文件放到Assets下
1、使用Application.dataPath获取路径
string json = File.ReadAllText(Application.dataPath+"/taskInfo.json");
Root root = JsonUtility.FromJson<Root>(json);
举例
{ "msg": "成功!", "code": 1, "data": { "teacher": "cao", "age": "52", "subject": "math", "students":[ { "name": "wang", "age": "20", "grade": "79", "number": "6" }, { "name": "zhang", "age": "22", "grade": "91", "number": "5" } ] } }
复制
需要写好实体类来接受
public class Root { public string msg; public int code; public DataM data; } public class DataM { public string teacher; public int age; public int subject; public List<Student> students; } public class Student { public string name; public int age; public int grade; public int number; }
复制
现在读取Resources文件夹下的json文件,这里我是用的是LitJson插件
//获取json数据(此处读取本地上的json文件) TextAsset jsonTextAsset = Resources.Load<TextAsset>(jsonFilePath); string jsonInfo = jsonTextAsset.text; //json转类 Root root = JsonMapper.ToObject<Root>(jsonInfo); //遍历获得数据 foreach (var DataM in root.data) { Debug.Log(DataM.techer); //————> cao Debug.Log(DataM.age); //————> 52 Debug.Log(DataM.students[0].name); //————> wang Debug.Log(DataM.students[1].grade); //————> 91 }
复制