我正在尝试访问从Google附近的地方API接收到的JSON中的所有类型值。
JSON包含一个称为“结果”的部分,该部分中包含找到的每个位置的部分。不同的地方用花括号隔开,我不明白如何从第一组之外的任何数据中获取数据。
这里有一个(缩短的)JSON结果来演示我在说什么。
{
"html_attributions" : [],
"results" : [
{
"types" : [ "locality", "political" ],
"vicinity" : "Oakville"
},
{
"types" : [ "university", "point_of_interest", "establishment" ],
"vicinity" : "1430 Trafalgar Road, Oakville"
}
]
}
我的Unity项目中的代码段:
UnityWebRequest www = new UnityWebRequest(url);
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
string results = www.downloadHandler.text;
PlaceClasses placeData = JsonUtility.FromJson<PlaceClasses>(results);
Debug.Log("placedata is " + placeData.results[0].types[0]);
调试消息将打印位置的第一种类型(位置)。我如何也可以从第二位访问类型? 结果中只有一个值,所以我不能超越结果[0]。
答案 0 :(得分:1)
输入
public static void Main(string[] args)
{
var json = @"{
'html_attributions' : ['attr1' ],
'results' : [
{
'types' : [ 'locality', 'political' ],
'vicinity' : 'Oakville'
},
{
'types' : [ 'university', 'point_of_interest', 'establishment' ],
'vicinity' : '1430 Trafalgar Road, Oakville'
}
]
}";
代码
public class X
{
public List<string> HtmlAttributions { get; set; }
public List<Result> Results { get; set; }
}
public class Result
{
public List<string> Types { get; set; }
public string Vicinity { get; set; }
}
(...)
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() }
};
var x = JsonConvert.DeserializeObject<X>(json, settings);
Console.WriteLine(x.Results[0].Types[1]);
Console.WriteLine(x.Results[0].Vicinity);
输出
political
Oakville
代码
using Newtonsoft.Json.Linq;
(...)
JObject o = JObject.Parse(json);
var rs = o["results"];
foreach (var r in rs)
{
Console.WriteLine("-----");
Console.WriteLine(r);
}
输出
顺便说一句。 json中的数组未关闭。
-----
{
"types": [
"locality",
"political"
],
"vicinity": "Oakville"
}
-----
{
"types": [
"university",
"point_of_interest",
"establishment"
],
"vicinity": "1430 Trafalgar Road, Oakville"
}