Unity3D中读取json文件
发表于2018-09-03
在Unity的开发中,经常会用到Json来存储数据文件,而本篇文章要和大家分享下读取json文件的方法。
需要大家先下载jsondLL:
代码如下:
{
"height": 20,
"sites": [
{
"name": "testname",
"age": 10,
"data": [ 20, 12, 30, 55, 44 ]
},
{
"name": "google",
"age": 18,
"data": [ 20, 12, 30, 55, 44 ]
},
{
"name": "baidu",
"age": 30,
"data": [ 20, 12, 30, 55, 44 ]
}
]
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
public class ReadJson : MonoBehaviour {
// Use this for initialization
void Start () {
TextAsset text = Resources.Load<TextAsset>("jsonTest");
tmxClass jd = JsonMapper.ToObject<tmxClass>(text.text);
for (int i = 0; i < jd.sites.Count; i++)
{
Debug.Log(jd.sites[i].name + "/" + jd.sites[i].data.Count);
}
#region 测试1
/*
TextAsset text = Resources.Load<TextAsset>("jsonTest");
Hashtable jd = JsonMapper.ToObject<Hashtable>(text.text);
JsonData jd1 = jd["sites"] as JsonData;
for (int i = 0; i < jd1.Count; i++)
{
Debug.Log(jd1[i]["name"]);
}
Debug.Log("ht = " + jd["sites"].ToString());
Debug.Log("ht = " + jd1.Count);
Debug.Log("text :" + text.text);
//string json = "{\"test\":\"www.test\",\"test1\":\"www.test1\"}";
//Hashtable jd = JsonMapper.ToObject<Hashtable>(json);
//foreach (string str in jd.Keys)
//{
// Debug.Log("key = " + str + "/value = " + jd[str]);
//}
//Debug.Log("jd test = " + jd["test"]);
*/
#endregion
}
public class sites
{
public string name;
public int age;
public List<int> data;
}
public class tmxClass
{
public int height;
public List<sites> sites;
}
}
