tomas tomas - 9 months ago 58
C# Question

Deserialize Json with unknown count plugin

I'm trying deserialize Json with unknown count iteration. I get menu structure in this format:

[{
"id": 15,
"item": "menuTop",
"child": {
"id": 16,
"item": "subMenu",
"child": {
"id": 17,
"item": "Result",
"child": null
}
}
}]:


It's part of my json, so I have to check the last object that says child: null. Otherwise, it may has got more or less number of iteration.

Here is my code. But it doesn't work. I'm not sure if my class item is correct, especially property child

var result = JsonConvert.DeserializeObject<MenuItem>("mySerializedString");

class MenuItem
{
public long id { get; set; }
public string item { get; set; }
public List<MenuItem> child { get; set; }
}

Max Max
Answer Source

You must deserialize as List<MenuItem> and child must be a MenuItem not List

var result = JsonConvert.DeserializeObject<List<MenuItem>>(json);

class MenuItem
{
    public long id { get; set; }
    public string item { get; set; }
    public MenuItem child { get; set; }
}

UPDATE

As @Alexei Levenkov pointed out to me, and thank you, there are some tools that can create C# classes from a json file.

There are web sites where you can paste your json and it generate the C# classes you need to deserialize your json, for example json2charp

At this Stackoverflow question you can find more infos.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download