-2

The following JSON string is coming to an MVC Action:

[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]}]

I'm using the DeserializeObject method of the JavaScriptSerializer class to deserialize the JSON string, but I am not sure how to work with the converted array after I deserialize it.

var result = Request["nestable-output"];                       

JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var answer = json_serializer.DeserializeObject(result);

Is there any other way to do this?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Sayel
  • 19
  • 3
  • 1
    Have you used Google to do a simple search on this..? there are actually numerous examples / answers on how to do this on `SO` please show a little bit more effort on your part [Deserializing a JSON String](http://stackoverflow.com/questions/5502245/deserializing-a-json-file-with-javascriptserializer) – MethodMan Nov 10 '14 at 22:41
  • 1
    individuals do not get points for comments and comments are not answers.. look at this as well perhaps you need to follow some of the examples http://www.tomasvera.com/programming/using-javascriptserializer-to-parse-json-objects/ – MethodMan Nov 10 '14 at 23:10

1 Answers1

1

When you call DeserializeObject() on the JavaScriptSerializer class, the serializer does not have any hint as to what type of objects to deserialize into other than what it can infer from the JSON structure. So, when it sees a JSON array, it will use object[] and when it sees a JSON object it will use Dictionary<string, object>. Knowing this, you can get your data out by casting where needed:

foreach (Dictionary<string, object> item in (IEnumerable)answer)
{
    Console.WriteLine("id: " + item["id"]);
    if (item.ContainsKey("children"))
    {
        Console.WriteLine("children:");
        foreach (Dictionary<string, object> child in (IEnumerable)item["children"])
        {
            Console.WriteLine("   id: " + child["id"]);
        }
    }
}

But there's a better way. If possible, it is usually better to define some strongly typed classes and deserialize into those instead. For example, for your JSON we could create an Item class like this:

class Item
{
    public int Id { get; set; }
    public List<Item> Children { get; set; }
}

Then, we can use the Deserialize<T>() method instead of DeserializeObject(). Now it is obvious what type the data is and we can work with it easily like any other object.

List<Item> answer = json_serializer.Deserialize<List<Item>>(result);

foreach (Item item in answer)
{
    Console.WriteLine("id: " + item.Id);
    if (item.Children != null)
    {
        Console.WriteLine("children:");
        foreach (Item child in item.Children)
        {
            Console.WriteLine("   id: " + child.Id);
        }
    }
}

Does that help?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300