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(""));
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 (4)

  1. Mudassir says:

    Kindly Give Sample project if possible 🙂

  2. siddh says:

    Kindly Give Sample project if possible 🙂

  3. Sergio says:

    yes,. a simple project will be great

  4. Faizan Amjad says:

    To learn more about JSON parsing in windows store applications read following article…/how-to-store-json-data-in-windows-phone-8.aspx

Skip to main content