Streamlining the JSON Serialization

Thursday, 1 November 2007 03:26 by James

For a while now I have been using the Newtwonsoft.Json dll to generate my JSON objects. The documentation is pretty sparse and I had to do a lot of experimentation to figure out the best way to do it. I ended up with this base code.

myUCR_DepartmentsTableAdapters.MyUCR_DepartmentsTableAdapter deptTA = new myUCR_DepartmentsTableAdapters.MyUCR_DepartmentsTableAdapter();
myUCR_Departments.MyUCR_DepartmentsDataTable deptDT = new myUCR_Departments.MyUCR_DepartmentsDataTable();
deptTA.FillDepts(deptDT);
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
writer.WriteStartArray();

foreach (myUCR_Departments.MyUCR_DepartmentsRow deptRow in deptDT)
{
   writer.WriteStartObject();
   writer.WritePropertyName("deptID"); writer.WriteValue(deptRow.deptID.ToString());
   writer.WritePropertyName("dept"); writer.WriteValue(deptRow.department.ToString().Trim());
   writer.WriteEndObject();           
}
writer.WriteEndArray();
writer.Flush();
Response.Write(sw.GetStringBuilder().ToString());

 As you can see, that's a lot of code to serialize a simple datatable.

I wanted to find an easier way, so started browsing around. Googling for "JSON DataTable Serialization", I came across this article "A DataTable Serializer for ASP.NET AJAX" at denydotnet.com. What he did was to extend the JavaScriptConverter found in System.Web.Script.Serialization to serialize a DataTable. I looked through his code and decided to implement it.

Now here's how I do my serialization:

        MyUCR_LoginTableAdapter ta = new MyUCR_LoginTableAdapter();
        DataTable dt = ta.GetByTesting();
        JavaScriptSerializer toJSON = new JavaScriptSerializer();
        toJSON.RegisterConverters(new JavaScriptConverter[]{new JavaScriptDataTableConverter()});
        Response.Write(toJSON.Serialize(dt));

And what rocks is the object names are mapped to the column names in the database.

Cool

James

 

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Add comment


 

  Country flag

biuquote
  • Comment
  • Preview
Loading



James Johnson

My views and opinions on running a .NET User Group, web development, evangelizing, mentoring, utilizing the latest technologies, living as a gringo in a Latin family, and, of course, life in general.

Join BizSpark

BizSpark provides qualified Startups with FREE* software and support getting their idea up and running.
There is no charge for signing up. However a minimal fee of $100 is required when you leave the program.

Recent Comments