colinramsay.co.uk

Working with JSON and C# 3.0

08 May 2007

I've been using libraries such as NewtonSoft's JSON.NET or AjaxPro to serialize a class to JSON. There's something about my approach which didn't really sit too well, and C# 3 has an elegant solution.

Here's an extremely contrived example to illustrate the point; I only want certain properties of Page to be sent as JSON:

public class PageController
{
	public void List()
	{
		Page[] allPages = Page.FindAll();

		DisplayablePage[] displayablePages = new DisplayablePage[];
	
		for(int i = 0; i < allPages.Length; i++)
		{
			string name = allPages[i].Name;
		
			displayablePages[i] = new DisplayablePage(name);
		}
		
		RenderText(Json.Serialize(displayablePages));
	}
	
	private class DisplayablePage
	{
		private string _name;

		public string Name
		{
			get { return _name; }
			set { _name = value; }
		}
		
		public DisplayablePage(string name)
		{
			_name = name;
		}
	}
}

Now, as you can see I have created the DisplayablePage class which will then be serialized as JSON. However, this class is never used anywhere else. It's a bit of a crutch for what I'm trying to do. In C# 3.0, I can use anonymous types to achieve the same goal:

public class PageController
{
	public void List()
	{
		Page[] allPages = Page.FindAll();

		object[] displayablePages = new object[];
	
		for(int i = 0; i < allPages.Length; i++)
		{
			string name = allPages[i].Name;
		
			displayablePages[i] = new { Name = name };
		}
		
		RenderText(Json.Serialize(displayablePages));
	}
}

I can create an anonymous type which will then be serialized as JSON, reducing the code necessary to achieve my goal. I'm using an object array now, rather than an array of a fixed type, which you could argue isn't as good as in the previous sample. In my eyes it's ok, because we're only using this array for this specific purpose.