Tuesday, January 24, 2012

Converting .Net Object In To JSON Object ASP.Net MVC

If you want to convert your .Net object in to a JSON object in the view the first thing you can use is to use System.Web.Script.Serialization.JavaScriptSerializer object and convert it in to JSON.
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();


var s = @serializer.Serialize(Model);


This is MVC3 Razor syntax. The problem here is in the @ sign it will again HTML encode the JSON object which lead you to flowing error.
var s = { "Name":"a","Id":1};
Create:228Uncaught SyntaxError: Unexpected token &

To avoid this we can use HTML.Raw() helper method like below.
var s = @HTML.Raw(serializer.Serialize(Model));

The easiest and the most reusable way of doing it is to write a helper method link this,
public static MvcHtmlString ToJson(this HtmlHelper html, object obj)
  JavaScriptSerializer serializer = new JavaScriptSerializer();
  return MvcHtmlString.Create(serializer.Serialize(obj));

And then in the view we can use this helper method


  1. This is a good post can you please update some more about j son. I have some requirement like convert a Web API to j son and XML.
    Please write something about it and it is more helpful if you use sime images or demo download which was error free.
    Atul D

    1. I think you can request whatever the data type from the client side and get the relevant datatype back. This is one of the most advantages of web api. You just need to set the content type of the request .
      Accept or Content-Type request headers. http://stackoverflow.com/questions/9847564/how-do-i-get-mvc-4-webapi-to-return-json-instead-of-xml-using-chrome