Parsing complex objects in JSON with c#.NET v3.5 and above

How can we de-serialise a JSON string containing a list of complex objects in c#? Quite easily actually, but it took me a while to suss it out, so I'm putting it online here in the hope that someone finds it useful.

Consider a class called LinkItem, and a web service that spits out a List<LinkItem> Result.

public class LinkItem
{
	public int LinkItemId { get; set; }
	public String Url { get; set; }
	public String Title { get; set; }
	public DateTime TimeStamp { get; private set; }

	public LinkItem()
	{
	}
}

It produces a JSON string in the format:

{
   "Result":[
      {
         "LinkItemId":1,
         "Url":"http://www.link1.co.uk/",
         "Title":"Link One",
         "TimeStamp":"\/Date(1376220136723-0000)\/"
      },
      {
         "LinkItemId":2,
         "Url":"http://www.link2.co.uk/",
         "Title":"Link Two",
         "TimeStamp":"\/Date(1376220137137-0000)\/"
      }
   ]
}

Working out how to parse from this JSON string back into a List of objects was tough. Turns out that c#.Net 3.5+ does have a class for doing this though, and that class is the DataContractJsonSerializer  which you'll find in the System.Runtime.Serialization.Json namespace (reference System.Runtime.Serialization in your project).

I feel like the best thing is just to show you my solution for parsing it. 

public class LinkItem
{
    public int LinkItemId { get; set; }
    public String Url { get; set; }
    public String Title { get; set; }
    public DateTime TimeStamp { get; set; }
}

public class LinkItems
{
    public List<LinkItem> Result { get; set; }
}

static void Main(string[] args)
{
    ...
    WebRequest request = WebRequest.Create(url);
    WebResponse ws = request.GetResponse();
    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(LinkItems));
    LinkItems linkItems = (LinkItems)jsonSerializer.ReadObject(ws.GetResponseStream());
}

Hopefully this helps someone out. I sure could have used this example at the weekend when it took me a couple of hours to work this out.