Archive
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}