Serialize and Deserialize to JSON from ASP.NET

Its very easy to serialize an object to .NET
Simply create some object, normally a custom class with some attributes.
Normally you have a list of these and you want to serialize to JSON to use it from client side code.

If you do the following

var s = new System.Web.Script.Serialization.JavaScriptSerializer();
string resultJs = s.Serialize(result);

you will end up with a JSON array that you were looking for:

[ 
  { "Desc" : "Corn 100 ",
    "ItemNo" : "123456",
    "OriginalQty" : 50,
    "Qty" : 50,
    "UnitPrice" : 10.21
  } ,
  { "Desc" : "Ice 100 ",
    "ItemNo" : "323456",
    "OriginalQty" : 50,
    "Qty" : 50,
    "UnitPrice" : 10.50
  } ,
  { "Desc" : "Meat 100 ",
    "ItemNo" : "423456",
    "OriginalQty" : 50,
    "Qty" : 50,
    "UnitPrice" : 10.11
  } 
  
]

However if you try to deserialize this back into an object by running

var json = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = json.Deserialize<ShoppingCartItem[]>(jsonItemArray);
    

You will get a NULL type Exception.

The solution is to create a simple resolver as follows

    using System;
    using System.Web;
    using System.Web.Compilation;
    using System.Web.Script.Serialization;
    
    namespace XYZ.Util
    {
        /// <summary>
        /// as __type is missing ,we need to add this
        /// </summary>
        public class ManualResolver : SimpleTypeResolver
        {
            public ManualResolver() { }
            public override Type ResolveType(string id)
            {
                return System.Web.Compilation.BuildManager.GetType(id, false);
            }
        }
    }
    

2) Use it to serialize

    var s = new System.Web.Script.Serialization.JavaScriptSerializer(new XYZ.Util.ManualResolver());
    string resultJs = s.Serialize(result);
    lblJs.Text = string.Format("<script>var resultObj = {0};</script>", resultJs);
    

You will get something like the following this time (note new __type included this time)

[ 
  { 
    "__type":"XYZ.Data.Entities.ShoppingCartItem, XYZ.Data, Version=1.7.1.0, Culture=neutral, PublicKeyToken=null",
    "Desc" : "Corn 100 ",
    "ItemNo" : "123456",
    "OriginalQty" : 50,
    "Qty" : 50,
    "UnitPrice" : 10.21
  } ,
  { 
    "__type":"XYZ.Data.Entities.ShoppingCartItem, XYZ.Data, Version=1.7.1.0, Culture=neutral, PublicKeyToken=null",
    "Desc" : "Ice 100 ",
    "ItemNo" : "323456",
    "OriginalQty" : 50,
    "Qty" : 50,
    "UnitPrice" : 10.50
  } ,
  { 
    "__type":"XYZ.Data.Entities.ShoppingCartItem, XYZ.Data, Version=1.7.1.0, Culture=neutral, PublicKeyToken=null",  
    "Desc" : "Meat 100 ",
    "ItemNo" : "423456",
    "OriginalQty" : 50,
    "Qty" : 50,
    "UnitPrice" : 10.11
  } 
  
]

3) Use it to deserialize

    System.Web.Script.Serialization.JavaScriptSerializer(new XYZ.Util.ManualResolver());
    var result = json.Deserialize<ShoppingCartItem[]>(jsonItemArray);
    

References: Comment by Manuel Abadia on ASP.NET AJAX Extensions Internals – Web Service Proxy Generation

3 comments on “Serialize and Deserialize to JSON from ASP.NET”

  1. Sireesha Reply

    Hi,
    Im trying to deserialize json response using c#. net using 3.5 framework.

    Could you please provide small sample application to deserialize json response.

    Its very urgent.
    Thanks in advance

    Sireesha

    • Sameer Alibhai Reply

      you can try
      object someObject = null;
      var json = new System.Web.Script.Serialization.JavaScriptSerializer();
      var result = json.Deserialize(inputString);

      See if that works. in my case i had a particular object i created (ShoppingCart) but you can try with generic object see if it works

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>