Deserializing JSON - how to ignore the root element?

Nikolaos Georgiou picture Nikolaos Georgiou · Dec 4, 2012 · Viewed 15.1k times · Source

I'm consuming a WCF service that returns JSON results wrapped inside the 'd' root element. The JSON response looks like this:

{"d":[
  {
    "__type":"DiskSpaceInfo:#Diagnostics.Common",
    "AvailableSpace":38076567552,
    "Drive":"C:\\",
    "TotalSpace":134789197824
  },
  {
    "__type":"DiskSpaceInfo:#Diagnostics.Common",
    "AvailableSpace":166942183424,
    "Drive":"D:\\",
    "TotalSpace":185149157376
  }
]}

I don't want to use dynamic typing, I have my class Diagnostics.Common.DiskSpaceInfo that I want to use when deserializing.

I am using Json.NET (Netwonsoft JSON).

The question is how to tell it to ignore the root element (that 'd' element) and parse what is inside.

The best solution I have so far is to use an anonymous type:

DiskSpaceInfo[] result = JsonConvert.DeserializeAnonymousType(json, new
    {
        d = new DiskSpaceInfo[0]
    }).d;

this actually works but I don't like it very much. Is there another way? What I would like is something like:

DiskSpaceInfo[] result = JsonConvert.Deserialize(json, skipRoot: true);

or something like that...

Answer

keyr picture keyr · Dec 4, 2012

If you know what to search like in this case "d" which is a root node then you can do the following.

JObject jo = JObject.Parse(json);
DiskSpaceInfo[] diskSpaceArray = jo.SelectToken("d", false).ToObject<DiskSpaceInfo[]>();

If you simply want to ignore the root class which you do not know then you can use the "@Giu Do" solution just that you can use test2.ToObject<DiskSpaceInfo[]>(); instead of the Console.Write(test2);

        JObject o = JObject.Parse(json);
        if (o != null)
        {
            var test = o.First;
            if (test != null)
            {
                var test2 = test.First;
                if (test2 != null)
                {
                    DiskSpaceInfo[] diskSpaceArray = test2.ToObject<DiskSpaceInfo[]>();
                }
            }
        }