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?