2

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?

1
  • 1
    What does the error say? Commented Dec 14, 2014 at 15:50

2 Answers 2

1

Have you tried this?

public class MenuJson
{
    [JsonProperty("id")]
    public string id { get; set; }

    [JsonProperty("children")]
    public List<MenuJson> children { get; set; }
}

var list = JsonConvert.DeserializeObject<List<MenuJson>>(json);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I've just tried, I got the same error, see my edit for the error
@bramalho, I think the problem is that you are trying to put into an OBJECT (single), a COLLECTION (because your JSON is a collection). Try my updated answer
1

Here's an working example:

public void Test()
    {
        string json = "[{\"id\":12},{\"id\":2,\"children\":[{\"id\":3},{\"id\":4}]}]";

        var objects = JsonConvert.DeserializeObject<List<MenuJson>>(json);

        foreach (var property in objects)
        {
            var id = property.id;
            foreach (var child in property.children)
            {
                //child
            }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.