Unity 之json解析
首先创建解析模型脚本
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class JsonObjectModel {
//对应Json中属性 名字要一样
[SerializeField]
public string name;
[SerializeField]
public int age;
public JsonObjectModel()
{
}
public JsonObjectModel(string _name, int _age)
{
this.name = _name;
this.age = _age;
}
}
[Serializable]
public class JsonList
{
[SerializeField]
public List<JsonObjectModel> nameList;
public JsonList()
{
}
public JsonList(List<JsonObjectModel> _nameList)
{
this.nameList = _nameList;
}
}
2.创建解析脚本
using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class JsonDeserialize : MonoBehaviour {
// Use this for initialization
void Start () {
foreach (var info in ReadJson().nameList)
{
Debug.Log(info.name+ " " + info.age);
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
List<JsonObjectModel> temp = new List<JsonObjectModel>();
temp.Add(new JsonObjectModel("人物1", 22));
temp.Add(new JsonObjectModel("人物2",33));
WritePath(temp,GetJsonPath());
}
}
private JsonList ReadJson()
{
string content = File.ReadAllText(GetJsonPath());
JsonList jsonList = JsonMapper.ToObject<JsonList>(content);
return jsonList;
}
private void WritePath(List<JsonObjectModel> configList, string path)
{
File.WriteAllText(path, JsonUtility.ToJson(new JsonList(configList)));
Debug.Log("保存成功!");
}
private string GetJsonPath()
{
return string.Format(Application.dataPath + "/Config/JsonData.json");
}
}
3.jsonData.json文本创建,格式如下
{
"nameList": [
{
"name": "人物1",
"age": 22
},
{
"name": "人物2",
"age": 33
}
]
}
注意:配置文件的路径Config目录下