Saturday, March 21, 2009

ASP.NET MVC and JSON

ASP.NET MVC 1.0 RTM was released with reference to obsolete code as follows. This code snippet can be found in the JsonResult object's ExecuteResult method.


#pragma warning disable 0618
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(serializer.Serialize(Data));
#pragma warning restore 0618



Why is this important?

Well the JavaScriptSerializer has been marked as obsolete for one. Also it does not correctly handle objects trees, especially when they are dynamic. There are other blogs on this subject.

This is fairly easily to work-around, although hopefully MS will fix this in the next release. To rectify the situation, use the following derivative JsonResult class that uses the
DataContractJsonSerializer serializer. The important part of the class is the ExecuteResult method which with the serializer is as simple as


public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");

HttpResponseBase response = context.HttpContext.Response;

if (!String.IsNullOrEmpty(ContentType))
response.ContentType = ContentType;
else
response.ContentType = "application/json";

if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;

if (Data != null)
{
string output = string.Empty;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(Data.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
output = Encoding.Default.GetString(ms.ToArray());

byte[] bytes = Encoding.Unicode.GetBytes(output);
output = encoding.GetString(Encoding.Convert(Encoding.Default, encoding, bytes));
}
response.Write(output);
}
}


Now you have the basics to use the more powerful DataContract serializers to serializer your object into Json.

0 comments:

Post a Comment