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}
simply awesome…..it helps me lot
Silmple and Very USeful Example.. Thank uuuuuuuuu
Prefect example. Helped me a lot… Thanks you
Thank you. The simple example I needed to understand deserialization of JSON in C#
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.
Thanks lot…
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
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;
}