获取天气信息,首先要找到提供天气数据的接口,我使用的是高德地图免费为咱们提供的,网址为 https://lbs.amap.com/api/webservice/guide/api/weatherinfo web
使用的前提是注册一个高德帐号用来获取返回参数中所须要的key,步骤很简单,按照网址中的提示来就能够了。json
获取网络数据,须要用到UnityWebRequest类,经过它的Get方法能够获得网址中的信息,返回的是含有URI中数据的UnityWebRequest对象。api
UnityWebRequest re = UnityWebRequest.Get(string uri);
接下来使用它的 downloadHandler 方法来管理从远程服务器中接受的数据(想了解更多用法能够去看官方文档)服务器
string JsonData = re.downloadHandler.text; //text返回的是经过UTF-8编码的字符串
好了,如今咱们已经拥有JSON类型的天气数据了网络
序列化是将对象转化为字节序列的过程。在Unity中能够使用其自带的类进行序列化和反序列化 -> JsonUtility,下面是它包含的方法ide
咱们只须要使用它的FormJson方法来建立对象,官方给出的案例是ui
using UnityEngine; [System.Serializable] public class PlayerInfo { public string name; public int lives; public float health; public static PlayerInfo CreateFromJSON(string jsonString) { return JsonUtility.FromJson<PlayerInfo>(jsonString); } // Given JSON input: // {"name":"Dr Charles","lives":3,"health":0.8} // this example will return a PlayerInfo object with // name == "Dr Charles", lives == 3, and health == 0.8f. }
在内部,此方法使用 Unity 序列化器;所以建立的类型必须受序列化器支持,它必须是使用 Serializable 属性标记的普通类/结构,而且为public类型,天气数据也能够用相似方法进行读取this
//定义结构体存储json返回的天气信息 [Serializable] public struct MainJson { public string status; public string count; public string info; public string infocode; public List<LiveInfo> lives; } [Serializable] public struct LiveInfo { public string provice; public string city; public string adcode; public string weather; public string temperature; public string winddirection; public string windpower; public string humidity; public string reporttime; } MainJson j = JsonUtility.FromJson<MainJson>(re.downloadHandler.text); if (j.status == "0") { print(j.info); } else { string cityName = j.lives[0].provice + j.lives[0].city; }
这是我写的一个小demo(不是完整代码)。编码
值得注意的是,结构体中定义的变量名要和JSON中的数据一致,名称一致,不须要的数据能够不定义。 下面是效果图spa