I am trying to access all the categories in the first level within a Foursquare response:-
{
"meta": {
"code": 200
},
"response": {
"categories": [{
"id": "4d4b7104d754a06370d81259",
"name": "Arts & Entertainment",
"pluralName": "Arts & Entertainment",
"shortName": "Arts & Entertainment",
"icon": {
"prefix": "https:\/\/foursquare.com\/img\/categories\/arts_entertainment\/default_",
"sizes": [32, 44, 64, 88, 256],
"name": ".png"
},
"categories": [{
"id": "4bf58dd8d48988d1e1931735"
using JSON.NET:-
JObject o = JObject.Parse(FoursquareObject.GetCategories());
IList<string> categories = o.SelectToken("categories[0]").Select(s => (string)s).ToList();
Where FoursquareObject.GetCategories()
returns the response as a string. I also tried:-
JArray categories = (JArray)o["categories"];
var categories = (string) o["response[0].categories"];
...and numerous variations of, just to see the response in the variable and always get 'Object reference' or 'cannot be {null}' errors. I know I'm close, but for the life of me can't work out how to get at the 'categories' part of the response...
Can anyone point me in the right direction?
Help is appreciated. ;)
UPDATE:
Thanks to the answers from L.B and Meklarian, I added this code (and variants of):-
dynamic four = JsonConvert.DeserializeObject(FoursquareObject.GetCategories());
foreach (var cat in four)
{
context.Response.Write(cat.response.categories.id);
}
But regardless of what I try in the Write()
, I always get:-
'Newtonsoft.Json.Linq.JProperty' does not contain a definition for 'response'
I tried loads of combinations, no-luck. I checked the output from the JSON file, I get pure JSON response as a string. Just a note, that categories can exist in categories, hence why the JSON seems to look broken. I assure you it's not. I'm completely stuck!