0

所以在做一个网络请求之后,我得到了这个 JSON 字符串:

{"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、国家、地区等的 City 类,我希望能够将每个类分别保存在一个列表中,以便我可以将它们添加到应用程序的列表视图中。

我试过这个:

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"];
                }
            }
        }

但是我不断收到解析错误。我尝试了一些东西,但没有一个最终工作。我如何分别解析数组的每个部分并将其保存到城市列表中。谢谢

4

1 回答 1

9

你应该使用DeserializeObject. 这是一个例子:

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
于 2013-11-12T23:17:29.937 回答