1
votes

What is the proper way to deserialize this JSON string? It is simply an array of dictionaries where each dict has a "title" and "children" where children is another array of dicts.

I am using this as a TreeView item source, but the treeview only displays the Title1 > Child1 because I assume something is wrong with the deserializing I'm doing. I also try to print out Child1's first child but can't figure out how to do it. The code below has an invalid cast exception.

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

List<Dictionary<string, object>> marr = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(s);
mTreeView.ItemsSource = marr;

List<Dictionary<string,object>> cs = (List<Dictionary<string,object>>)marr[0]["children"];
Debug.WriteLine(cs[0]["title"]);
3
json2csharp.com good online tool for this - outcoldman
I don't see why you want to create classes out of a JSON string. I don't plan on breaking my code simply because the JSON string format changes. - user317033

3 Answers

2
votes

Looks to me like you have the following:

class MyObject
{
    public string title { get; set; }
    public List<MyObject> children { get; set; }
}

var deserialized = JsonConvert.DeserializeObject<List<MyObject>>(s);

And no, there's no dictionary here, because:

  • Try as I might, I don't see a "dictionary" here so much as a recursive list of the object above, and
  • This is the actual definition of the object your want out anyway, so you can take advantage of all the benefits of having a real type, rather than just a dictionary of strings.

Note to address your comments: If the JSON string changes, it will not break your code; extraneous properties will be ignored and missing properties will correctly get set to null.

1
votes

https://codetitans.codeplex.com/

codetitans JSON supports correct parsing of JSON into array/dict of primitives as follows:

JSonReader jr = new JSonReader();
IJSonObject json = jr.ReadAsJSonObject(s);
Debug.WriteLine(json[0]["children"][0]["title"]);

As far as I can tell it is the only C# library that does.

0
votes

It looks like you can do this with JSON.NET out of box currently

var @object = JsonConvert.DeserializeObject(s)
var slightlyMoreUsefulObject = (JArray)@object;

var actualObject = slightlyMoreUsefulObject[0]

var topLevelTitle = actualObject["title"]

var children = actualObject["children"]
var firstChild = children[0]
var firstChildTitle = firstChild["title"]