Monday, 22 August 2016

c#: How can I read / parse a JSON file?

I was tasked with iterating through the JSON results generated by a REST API. I looked at several options such as

dynamic array = JsonConvert.DeserializeObject(jsondataasstring)

but I finally ended on using NewtonSoft.JSON to parse the data. The code is as follows:

// get the json data. in my case, I am reading it from a sample file from my MVC app
using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/App_Data/sample.json")))
        json = reader.ReadToEnd();

JObject jObj = JObject.Parse(json);

// navigate to the area in the object tree that you require

var messages = jObj["response"]["data"]["messages"];

// I now have a messages array that I can iterate through
foreach(var item in messages)
  // Write out the property 'title'
  Console.WriteLine(string.Format("The title is {0}", (string)item["title"]));

No comments:

Post a comment