Unity使用Litjson读取多级json数据(天气数据)
Litjson是什么就不多介绍了,我们从json数据开始讲起。以下为某api提供商提供的天气数据,我们一眼看出就是json数据格式,而且属于比较复杂的多级数据。
{"msg":"success","result":[{"airCondition":"良","city":"南京","coldIndex":"低发期","date":"2017-04-20","distrct":"南京","dressingIndex":"单衣类","exerciseIndex":"比较适宜","future":[{"date":"2017-04-20","dayTime":"阴","night":"多云","temperature":"22°C / 14°C","week":"今天","wind":"北风 4~5级"},{"date":"2017-04-21","dayTime":"多云","night":"多云","temperature":"22°C / 10°C","week":"星期五","wind":"西风 4~5级"},{"date":"2017-04-22","dayTime":"晴","night":"多云","temperature":"21°C / 10°C","week":"星期六","wind":"北风 小于3级"},{"date":"2017-04-23","dayTime":"多云","night":"多云","temperature":"23°C / 13°C","week":"星期日","wind":"南风 小于3级"},{"date":"2017-04-24","dayTime":"多云","night":"阴","temperature":"26°C / 17°C","week":"星期一","wind":"东南风 小于3级"},{"date":"2017-04-25","dayTime":"阴","night":"阴","temperature":"20°C / 16°C","week":"星期二","wind":"北风 3~4级"},{"date":"2017-04-26","dayTime":"局部多云","night":"局部多云","temperature":"22°C / 12°C","week":"星期三","wind":"东北偏北风 3级"},{"date":"2017-04-27","dayTime":"局部多云","night":"少云","temperature":"23°C / 13°C","week":"星期四","wind":"东南偏东风 2级"},{"date":"2017-04-28","dayTime":"少云","night":"局部多云","temperature":"24°C / 14°C","week":"星期五","wind":"西风 3级"},{"date":"2017-04-29","dayTime":"少云","night":"晴","temperature":"27°C / 16°C","week":"星期六","wind":"西南偏西风 4级"}],"humidity":"湿度:84%","pollutionIndex":"57","province":"苏","sunrise":"05:31","sunset":"18:37",
"temperature":"18℃","time":"07:40","updateTime":"20170420075356","washIndex":"比较适宜","weather":"多云","week":"周四","wind":"西北风3级"}],"retCode":"200"}
这样直接看这一大串的数据,是很疼的一件事,我们使用json在线阅读器来整理下结构:
这样看起来好很多了,我们再将数据依次展开:
我们发现在result数组下还嵌套了多个数组,这就是今天说的多级json数据。
我们回头看一眼第一张还没展开的图,有三个数据项:msg,result[],和retcode,那么这三个怎么读取呢?我们过下流程:
1.在unity的文件目录中新建Plugins文件夹然后将网上下载的litjson.dll拖放到该目录中。
2.新建monobehavior脚本,例如:weatherTest.cs
3.使用using litjson,引入litjson。
4.定义一个string 类型的变量用来承接url,即json文件的地址。
5.编写协程函数并调用。
6.读取json
完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; public class weatherTest : MonoBehaviour { void Start () { StartCoroutine (GetJsonFile()); } IEnumerator GetJsonFile() { if (Util.m_url.Length > 0) { WWW www = new WWW(Util.m_url); if (www != null) { yield return www; } JsonData jd = LitJson.JsonMapper.ToObject (www.text); //读取第一级 string result = (string)jd["msg"]; JsonData jdItems = jd ["result"]; //读取第二级 string city2 = (string)jdItems [0] ["city"]; //读取第三级 string temp = (string)jd["result"][0]["future"][0]["temperature"]; Debug.Log ( city2 + " " + temp); } }
U3DC原创文章禁止非授权转载。2017.4.20