Monday 23 March 2015

ASP.NET Tips #29 - Use JValue in JSON.Net to parse complex JSON objects

When parsing the JSON response from an API, it's not always easy to model the response perfectly in C#. Fortunately, you may only need part of the response. This is where the static JValue class in JSON.Net comes in handy.

If you've got your response string, you can parse it into a dynamic type and then access the object in whatever way you need, so long as you know its structure:

using Newtonsoft.Json.Linq;
dynamic json = JValue.Parse(response_string);
foreach (dynamic something in json)
{
   string name = something.name;
   int count = Convert.ToInt32(something.total);
}

It's quite handy and much easier than trying to model a giant POCO after some large JSON response.

No comments :

Post a Comment