I get this string on my controller:
"[{\"id\":12},{\"id\":2,\"children\":[{\"id\":3},{\"id\":4}]}]"
I want to parse this, and create one foreach inside other foreach to get the parents and children.
I've been trying this:
var object = JsonConvert.DeserializeObject<MenuJson>(json);
where MenuJson is:
public class MenuJson
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("children")]
public List<string> children { get; set; }
}
I got this erro:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'AIO.Controllers.AdminMenuController+MenuJson' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
And I tried other approach:
var objects = JsonConvert.DeserializeObject<JObject>(json);
foreach (var property in objects)
{
var id = property.Value;
foreach (var innerProperty in ((JObject)property.Value).Properties())
{
var child = property.Value;
}
}
Both I got errors when I try to convert the string.
My question is, How can I make this working?
And for my string, which approach is the best for my needs?