Reputation: 5189
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"}]}
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.
I have tried this:
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
Upvotes: 0
Views: 247
Reputation: 56536
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
Upvotes: 9