[英]Populate JSON data to dropdown list in Unity using C#
我有一个来自Openweathermap的城市的JSON文件。 并希望使用C#将城市名称放入Unity的下拉列表中。 这个怎么做?
JSON文件
{
"id": 2163306,
"name": "Holgate",
"country": "AU",
"coord": {
"lon": 151.416672,
"lat": -33.400002
}
},
{
"id": 2164949,
"name": "Gooramadda",
"country": "AU",
"coord": {
"lon": 146.550003,
"lat": -36
}
},
{
"id": 2157716,
"name": "Miepoll",
"country": "AU",
"coord": {
"lon": 145.466675,
"lat": -36.616669
}
},
{
"id": 2148406,
"name": "Steiglitz",
"country": "AU",
"coord": {
"lon": 144.183334,
"lat": -37.883331
}
},
使用Unity的JsonUtility,您必须先定义完整的结构,然后才能反序列化它。
[Serializable]
public class Data
{
public string id;
public string name;
public string country;
public Coord coord;
}
[Serializable]
public class Coord
{
public float lon;
public float lat;
}
Data myData = JsonUtility.FromJson<Data>(json);
就个人而言,当您只对json结构的一部分感兴趣时,我更喜欢使用Json.Net 。
您将可以执行以下操作:
JObject jRoot = JObject.Parse(json);
foreach (JObject jCity in jRoot)
{
string cityName = jCity["name"].Value<string>();
// add cityName to drop down list
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.