How to parse a Json file in WinRT application using C#?


(It Soft) #1

What is the best approach to read and parse a Json file in a WinRT Application project using C# (and optionally writing it too)?


(Kunni Can) #2

WinRT comes with that feature integrated, you can easily use Windows.Data.Json namespace.


(isoftech) #3

WinRT & UWP makes it really easy to use (read/parse/write) json files, without the need for any 3rd part libraries or custom hard coding.

Here is a little basic example:

using Windows.Data.Json;
 
JsonObject myStuff = new JsonObject();
 
// Now you can manipulate that as you wish.
// There are tons of JsonObjects and Classes under the namespace Windows.Data.Json.
// Take enough time to discover them well enough.

You can Parse a json string like this:

JsonObject jsonObject = JsonObject.Parse(jsonString);

// you can read a specific property value from json like this
var PropertyValue = jsonObject.GetNamedString(propertyKey, "");

// You can as well use 'GetNamedValue' instead of 'GetNamedString' to read custom type value.
IJsonValue PropertyValue = jsonObject.GetNamedValue(propertyKey);

Other supported JsonObject methods to read Json property values:

GetNamedString(): jsonObject.GetNamedString(PropertyKey, DefaultValue);
GetNamedNumber(): jsonObject.GetNamedNumber(PropertyKey, DefaultValue);
GetNamedBoolean(): jsonObject.GetNamedBoolean(PropertyKey, DefaultValue);
GetNamedValue(): jsonObject.GetNamedValue(PropertyKey);
GetNamedArray(): GetNamedArray(PropertyKey, new JsonArray());