Oct 22 2009

Simplify jqGrid JSON Generation

Category: .Net Framework | Web DevelopmentAlexRobson @ 15:09

So I’m trying to learn this jqGrid thing and so far it seems pretty cool but one thing was really bothering me: every example I saw that was using JSON was using anonymous types to create the required JSON format. Yuck city. Yes. I’m insane and whiney but there’s method to my madness.

Here’s the anonymous type approach:

var jsonData = new
{
    total = totalPages,
    page = page,
    records = totalRecords,
    rows = (
        from record in records
        select new
        {
            i = record.Id,
            cell = new string[] {
               record.Name, 
                record.Date.ToShortDateString(), 
                record.Description.ToString() 
            }
        }).ToArray()
};

Imagine you have to change any of these properties or the “schema” of your JSON output. What if you had to do that application wide? No refactoring tool can save you. Not only that, but you have to memorize/lookup the schema every time you create it. Typos will ruin you but there’s no compile time checking. These are just a few of the reasons I really dislike that approach.

What if you could do this instead?

var gridData = new jqGridData<Task>(
                tasks, 
                t => t.Id, 
                t => new object[]
                       {
                           t.Name,
                           t.Date,
                           t.Description
                       })
                       {     
							page = 1, 
							total = tasks.Count/pageSize,
							records = tasks.Count};

Now that’s more like it. Strongly typed, intellisense, compile time checked and refactor friendly. So here’s the code to make it happen (it’s very simple):

public class jqGridData<T>
	where T : class
{
	public int total { get; set; }
	public int page { get; set; }
	public int records { get; set; }
	public IList<jqGridRow<T>> rows { get; set; }

	public jqGridData(IList<T> list, Func<T, object> idMember, Func<T, object[]> columns)
	{
		rows = list.Select(i => new jqGridRow<T>(i, idMember, columns)).ToList();
	}
}
	
public class jqGridRow<T>
	where T : class
{
	public string id { get; set; }
	public string[] cell { get; set; }
	
	public jqGridRow(T rowInstance, Func<T, object> idMember, Func<T, object[]> columns)
	{
		id = idMember(rowInstance).ToString();
		cell = columns(rowInstance).Select(c => c.ToString()).ToArray();
	}
}

Right, not an earth-shattering discovery, certainly not going to change your life, but it does make using jqGrid with JSON simple.

Tags: ,

blog comments powered by Disqus