如何解析JSON数组C#? [英] How to parse a JSON array C#?
本文介绍了如何解析JSON数组C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,在执行Web请求之后,我得到了这个JSON字符串:
So after doing a web request, I get this JSON string back:
{"status":"okay","result":[{"id":8810,"country":"IE","region":"07","city":"Dublin","latitude":53.3331,"longitude":-6.2489,"comment":"407367 donkeys"},{"id":9688,"country":"IE","region":"04","city":"Cork","latitude":51.8986,"longitude":-8.4958,"comment":"454765 donkeys"},{"id":9963,"country":"IE","region":"06","city":"Donegal","latitude":54.65,"longitude":-8.1167,"comment":"315518 donkeys"}]}
我不确定如何解析它.我有一个包含ID,国家/地区,地区等的城市类,并且我希望能够将每个类分别保存在列表中,以便可以将它们添加到应用程序的列表视图中.
I'm not sure how to parse it. I have a City class that has id, country, region etc, and I would like to be able to save each one separately in a list so I can add them to a List View for an app.
我已经尝试过了:
JObject jobj = JObject.Parse(jsonString);
JToken jstatus = jobj["status"];
JToken jresult = jobj["result"];
status = (String)jstatus;
JArray arrayOfCities = JArray.Parse(jsonString);
if (status.Equals("okay"))
{
foreach (JObject o in arrayOfCities.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
id = p.Name + p.Value.ToString();// (String)jresult["id"];
country = (String)jresult["country"];
region = (String)jresult["region"];
city = (String)jresult["city"];
latitude = (String)jresult["latitude"];
longitude = (String)jresult["longitude"];
comment = (String)jresult["comment"];
}
}
}
但是,我一直在其中解析错误.我尝试了一些尝试,但最终都没有成功. 我如何分别解析数组的每个部分并将其保存到城市列表". 谢谢
However I keep getting parse errors in it. I tried a few things, but none end up working. How could I parse each part of the array separately and save it to a City List. Thanks
推荐答案
您应使用 DeserializeObject
.这是一个示例:
You should use DeserializeObject
. Here's an example:
public class CitiesResponse
{
public string Status { get; set; }
public List<City> Result { get; set; }
}
var response = JsonConvert.DeserializeObject<CitiesResponse>(jsonString);
// response.Result is your list of cities
这篇关于如何解析JSON数组C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文