Share via


Parsing JSON in Windows 8 store applications

Since you reached here I don’t think you’ll be interested why JSON is better than XML you are already using it, but if you are interested in why? Here is a great web page speaking about that (JSON: The Fat-Free Alternative to XML) but I think it’s a little bias towards JSON, but for me it’s better for two main reasons size and parsing time.

Getting the JSON String

For windows 8 store applications you’ll have to use the new HttpClient class in combination with the async/await keywoards for asynchronous web access. The GetAsync() methods returns a HttpResponseMessage containing the returned status code, response headers and content.

 var client = new HttpClient();
 HttpResponseMessage response = await client.GetAsync(new Uri("https://myapi.com/"));
 var jsonString = await response.Content.ReadAsStringAsync();
 

Parsing the JSON String (The Native way)

For the second part of your job, parsing the JSON string into an object, there is another new class available in .NET 4.5: JsonObject. You can feed the returned string into this class by using the constructor or the Parse() method. An exception will be thrown if the JSON string is invalid and can’t be parsed correctly. Once the parsing is done, the JsonObject behaves like a sort of dictionary from which you can get values by string indexers or methods.

 JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
 
 bool isSuccess = root.GetNamedString("status") == "ok";
 
 string type = root["type"].GetString();
 
 int size = (int)root.GetNamedNumber("size");
 
 JsonObject subObject = root.GetNamedObject("someSubObject");

Parsing the JSON String (The Easy way)

But my favorite library for JSON manipulations is JSON.NET. This library allows you to serialize and deserialize with a single line of code, directly to the objects you defined. You can use json2csharp to create your model, if you don’t have it available yet or you can use the newly visual studio introduced feature which will enable you to paste JSON as Classes, but in order to get that you have to install this update.

 var _Data = JsonConvert.DeserializeObject<T>(jsonString);

I hope you liked the post and I’m looking forward for your comments.

Comments

  • Anonymous
    November 14, 2013
    Kindly Give Sample project if possible :)
  • Anonymous
    May 15, 2014
    Kindly Give Sample project if possible :)
  • Anonymous
    September 04, 2014
    yes,. a simple project will be great
  • Anonymous
    December 27, 2014
    To learn more about JSON parsing in windows store applications read following articleblogs.msdn.com/.../how-to-store-json-data-in-windows-phone-8.aspx