I have MENUITEM and SCREEN entries defined in a root element MENUSTRUCT from a json string.
The important thing here is that a MENUITEM can contain other MENUITEMs or SCREENs.
I want to parse the whole json string with JSON.NET where I should receive a tree with MENUITEMs that can contain a huge chain of nested MENUITEMs or SCREEN entries.
I snipped a lot of the nested structures from the following json string:
{
"MENUSTRUCT": {
"-text": "GUI.Menu.Root",
"-image": "GUI.Menu.Home",
"-mask": "GUI.Menu.Home.Mask",
"-color": "#E0E0FF",
"-menuid": "MENUTREE",
"MENUITEM": [
{
"-text": "GUI.Menu.Text.00000003",
"-image": "GUI.Menu.Menu",
"-mask": "GUI.Menu.Menu.Mask",
"-color": "#C0C0FF",
"-menuid": "Menu.ID.00000003",
"SCREEN": [
{
"-id": "GUI.Dlg.StartupScreen",
"-text": "GUI.Menu.Text.00000103",
"-image": "GUI.Menu.Screen",
"-mask": "GUI.Menu.Screen.Mask",
"-menuid": "Menu.ID.00000103"
},
{
"-id": "GUI.Dlg.Calls",
"-text": "GUI.Menu.Text.Calls",
"-image": "GUI.Menu.Screen",
"-mask": "GUI.Menu.Screen.Mask",
"-menuid": "Menu.ID.00000203"
}
],
"MENUITEM": [
{
"-text": "GUI.Menu.Text.00000603",
"-image": "GUI.Menu.Menu",
"-mask": "GUI.Menu.Menu.Mask",
"-color": "#A0A0FF",
"-menuid": "Menu.ID.00000603",
"SCREEN": [
{
"-id": "GUI.Dlg.SpecialTrips",
"-text": "GUI.Menu.Text.00010603",
"-image": "GUI.Menu.Screen",
"-mask": "GUI.Menu.Screen.Mask",
"-menuid": "Menu.ID.00010603"
},
{
"-id": "GUI.Dlg.SpecialTrips",
"-text": "GUI.Menu.Text.00020603",
"-image": "GUI.Menu.Screen",
"-mask": "GUI.Menu.Screen.Mask",
"-menuid": "Menu.ID.00020603"
}
] // end of screen
}
] // end of nested menuitem
},
/* snipped following menuitems */
] // end of menuitem array
}
}
I tried to deserialize the whole thing with
JsonConvert.DeserializeObject<List<MenuItem>>(jsonString);
I have an object MenuItem which has a property of List<Screen> and one of List<MenuItem> but the whole thing doesn’t work out. I think the deserializer is not able to handle the nested MenuItems.
I also tried to parse the tree with JObject but I think this way you need to implement a lot of the parsing by yourself.
JObject obj = JObject.Parse(json);
var menuItems = from m in obj["MENUSTRUCT"]["MENUITEM"].Children() select m;
List<MenuEntry> menues = this.LoadMenuStructure(menuItems);
Here I have to make sure that I am on the correct JToken but I have no idea if I’m handling with a MenuItem or a Screen.
Is there no other, easier, way to deserialize the the json string without nesting me through all the structures?
Thanks in advance for your help.
Your original Script has errors in it and it has an additional blank
,towards the bottom. I removed the C#//Comments tags as well this should work for you nowJSONLint The JSON Validator