0

Searched my question and didnt find the answer, I have a JSON file like below:

{  
   "handle":"ABCD",
   "Tracks":{  
      "Design":{  
         "rating":402
      },
      "Development":{  
         "rating":1584,
         "reliability":"n/a"
      },
      "Specification":{  
         "rating":923,
         "reliability":"0.13"
      },
      "Conceptualization":{  
         "rating":895
      }
   }
}

I am getting a dynamic object of json:

dynamic dynObj;
dynObj = JsonConvert.DeserializeObject(content);

how can I get the name of "Tracks" item? I dont know how many tag like "Design" is there nor I know the name of them...

8
  • Where is your Server-Side Model? Where is that model that represents that JSON Object? Commented May 4, 2015 at 20:59
  • I am getting it from an API Commented May 4, 2015 at 21:00
  • Well, that would be how you access it. From that model, example.Tracks for example. Commented May 4, 2015 at 21:01
  • I can get all of the track items like dynObj["Tracks"], but I want to know how many items are there and the name of them to do sth else. Commented May 4, 2015 at 21:03
  • 2
    @MT467 Is there a reason that you need to use a dynamic type? Does the JSON data returned change frequently? Commented May 4, 2015 at 21:13

1 Answer 1

1

In your (dynamic) scenario, don't use dynamic, it does not make sense, since you are looking for schema information about the document, which becomes unavailable through the dynamic model.

So, get a JObject by calling JObject.Parse on your JSON data.

Then, get the keys as such (taken from the JObject.Properties documentation):

foreach (var prop in myJObject.Properties()) 
{ 
    //returns 'handle' and 'Tracks' for your root object
    Console.WriteLine("{0} - {1}", prop.Name, prop.Value); 
}

Or using the enumerator of the JObject:

foreach (var kvp in myJOBject) 
{
    Console.WriteLine("{0} - {1}", kvp.Key, kvp.Value);
}
Sign up to request clarification or add additional context in comments.

4 Comments

^this, or any of the JsonConvert.DeserializeObject overloads that take a type parameter.
I know handle and tracks are there, how about items under tracks?
@MT467 Repeat the same logic for the Value of the property.
@moarboilerplate We don't want a strongly typed value, as the type of the returned object is unknown, as I understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.