21. Mai 2014

JsonTree Library and Nuget Package for Quick and Easy JSON Parsing


Any time a piece of my software receives a JSON message it must dive into the JSON and extract parameters. Sometimes the JSON is deeply nested and parameters are buried inside arrays of objects of arrays.

I want to access these parameters quickly without dissecting the JSON by looping and if-ing through the layers. In other words: I want single line expressions to dive into JSON and extract values.

You can call it XPath for JSON, but a language integrated compiled way, which his much faster, than XPath and supported by IntelliSense (autocomplete).

Example JSON: 

[ "first", { "aString": "HelloWorld", "aNumber": 42 } ]
Extract the value 42:
var fourtytwo = json.List[1].Dictionary["aNumber"].Int;
The JsonTree library basically maps JavaScript Arrays to C# Lists and a JavaScript Objects to C# Dictionaries. It is then very easy to enumerate lists of dictionaries of lists, etc as single line expressions to extract values. Also, if looping is required, it is done on well known container classes List<...> and Dictionary<string,...>.

A more complex example:
var data = "[ { aInt: 41, bBool: true, bLong: 42000000000, cString: "43", dFloat: 3.14159265358979323 }, { aInt: 44, bLong: 45000000000, cString: "46" }, { aList: [ { aInt: 47, bString: "48" }, { aInt: 49, bString: "50" } ], bMap: { aInt: 51, bString: "52" } } ]";
Extracting the 50 as integer number. The 50 is a string value in a JS object (of key "bString") in a JS array (as second element) in a JS object (with key "aList") in a JS array (as third element).
var fifty = new JsonTree.Node(data).Array[2].Object["aList"].Array[1].Object["bString"].Int;
JsonTree uses either JavaScript notation with Array and Object as keywords or C# notation with List and Dictionary as keywords. Choose whatever you like more. 

The same as above in C# notation:
var fifty = new JsonTree.Node(data).List[2].Dictionary["aList"].List[1].Dictionary["bString"].Int;
Other examples:
var pi = new JsonTree.Node("{a:3.1415927}").Dictionary.First().Value.Float;

var pi = new JsonTree.Node("{a:3.1415927}").Dictionary["a"].Float;
You can use JsonTree as nuget package: https://www.nuget.org/packages/JsonTree/

Or check out the source code on Google code: https://code.google.com/p/json-tree/

JsonTree also includes a flexible JSON serializer which is used to create a easy to read debug view of the JSON structure. Browsing the JSON in debug mode is a real highlight. 



The serializer can also be used to add elements to a deserialized JSON node and re-serialize.

_happy_parsing()

PS: I know that I could use NewtonSoft JSON with C# dynamic and JObject
PS: I know that I could use LINQ

I like this way, because it relies only on plain old CLR objects, List and Dictionary.

Kommentar veröffentlichen