Home > ASP.NET > JavaScriptSerializer example

JavaScriptSerializer example

Today at work I had a chance to try the JavaScriptSerializer class in the System.Web.Script.Serialization namespace. My task was simple enough – deserialize a JSON string to an object then serialize the object back to a JSON string. Before I used the two methods Deserialize() and Serialize(), I had to create two classes for my experiment:

[Serializable]

public class LatLong

{

public double? latitude;

public double? longitude;

}

[Serializable]

public class MapView

{

public LatLong center;

public int? zoom;

}

So here is the code to deserialize and Serialize:

using System.Text;

using System.Web.Script.Serialization;

protected void Page_Load(object sender, EventArgs e)

{

string example = “{\”center\”:{\”latitude\”:\”49.266214\”,\”longitude\”:\”-122.998577\”},\”zoom\”:\”12\”}”;

JavaScriptSerializer serializer = new JavaScriptSerializer();

// Deserialize

MapView view = serializer.Deserialize<MapView>(example);

StringBuilder sb = new StringBuilder();

sb.Append(“center = (“ + view.center.latitude.ToString() + “, “ + view.center.longitude.ToString() + “)” + “<br/>”);

sb.Append(“zoom = “ + view.zoom.ToString());

litDeserialization.Text = sb.ToString();

// Serialize

string jsonString = serializer.Serialize(view);

litSerialization.Text = jsonString;

}

The result is like:

Deserialization:

center = (49.266214, -122.998577)
zoom = 12

Serialization:

{“center”:{“latitude”:49.266214,”longitude”:-122.998577},”zoom”:12}

  1. Pinakin
    March 30, 2010 at 8:59 am

    simply awesome…..it helps me lot

  2. Sumesh
    August 9, 2010 at 12:07 pm

    Silmple and Very USeful Example.. Thank uuuuuuuuu

  3. Sivakumar TN
    October 13, 2010 at 7:05 am

    Prefect example. Helped me a lot… Thanks you

  4. Connor Christian
    September 23, 2011 at 3:20 pm

    Thank you. The simple example I needed to understand deserialization of JSON in C#

  5. Igor
    March 15, 2012 at 8:48 am

    Fantastic! I learnt about JSON serialization/deserialization in just two minutes. Very concise and to the point. Thanks a lot Alex. Keep up the good work.

  6. Ravi
    July 13, 2012 at 5:52 pm

    Thanks lot…

  7. October 11, 2012 at 11:43 am

    Hi, nice blog. My string is
    My Json string is

    {“root”:[{“details”:{“id”:”1″,”code”:”110″,”description”:”lorem”,”netvalue”:”0.81″}}]}

    How can i deserialize using JavaScriptSerializer.

    Please help

  8. JJ
    November 8, 2012 at 10:29 pm

    Tsungy!

    Is it possible to create custom serialization attributes for class properties or do you need to create a complete custom serializer?

    e.g.

    public class LatLong
    {
    [SerializationInstruction]
    public double? latitude;
    public double? longitude;
    }

  1. No trackbacks yet.

Leave a reply to Connor Christian Cancel reply