JSonObject IEnumerable?

Apr 9, 2013 at 4:56 PM
I have a json string which contains an array of dictionaries for a TreeView. However the following won't compile as IJSonObject can't be converted to System.Collections.IEnumerable. Can IJSonObject be modified to support this case?

s = @"[{""title"":""Title1"",""children"":[{""title"":""Child1"",""children"":[{""title"":""grandchild1"",""children"":[{""title"":""Huh""}]}] }] }]";

JSonReader jr = new JSonReader();
IJSonObject json = jr.ReadAsJSonObject(str);
mTreeView.ItemsSource = json;
Apr 9, 2013 at 5:34 PM
I notice also you can't for example do a foreach. Is it difficult to add the necessary functions to serve as an array/dictionary?

I'm confused why none of the JSON parsers in C# properly parse JSON strings into a collection ( list / dictionary ) as JSON is a specification for a list and dictionary of primitive types. Your parser here is the only one that seems to do this allowing:


Although you currently are not implementing the collection interface apparently since foreach and setting the ItemsSource don't work. Since I can access the JSON through the array / dictionary [] operators I assume it is possible to implement the proper interface to allow this?
Apr 10, 2013 at 3:32 PM
Edited Apr 11, 2013 at 7:26 AM
IJSonObject doesn't allow enumeration by design. What would you like to enumerate - array items or object items - depending on the data inside? That would lead to lots of unexpected exceptions.

The enumeration approach, you like to have, could be done using ArrayItems and ObjectItems properties.
Take a look on following sample, that should answer all questions:
var str = @"[{""title"":""Title1"",""children"":[{""title"":""Child1"",""children"":[{""title"":""grandchild1"",""children"":[{""title"":""Huh""}]}] }] }, {""title"": ""Title2"" }]";

JSonReader jr = new JSonReader();
IJSonObject json = jr.ReadAsJSonObject(str);
IEnumerable items = json.ArrayItems;

foreach (var arrayItem in json.ArrayItems)
    foreach (var objItem in arrayItem.ObjectItems)
This will print out all the top-level property names, i.e.: title, children, title.