Serializing and deserializing objects in JSON
Published on Sunday, December 09, 2007
There are a few libraries out there to serialize or deserialize objects in
JSON. The "JavascriptObjectSerializer"
class in the "Microsoft.Web.Script.Serialization" namespace worked fine for me.
To use this class you need to add a reference to the "System.Web" and "System.Web.Extensions"
dlls. The "System.Web.Extensions" dll comes with Asp.Net AJAX.
Please note that the following recipe has been developed using .NET 2.0.
Here is how to serialize and deserialize an object:
using System;
using System.Web.Script.Serialization;
namespace SerializationJSON
{
class Program
{
public class Person
{
public string name;
public string age;
}
static void Main(string[] args)
{
// Instantiate new Person object, to be serialized
Person p = new Person();
p.age = "25";
p.name = "Giammarco Schisani";
// Instantiate a new JavaScriptSerializer
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
// Serialize
string pSerialized = javaScriptSerializer.Serialize(p);
// Echo serialized object to console
Console.WriteLine(pSerialized);
Console.WriteLine("Press any key to deserialize the string now...");
Console.ReadLine();
// Deserialize the result into a new object p1
Person p1 = javaScriptSerializer.Deserialize(pSerialized);
// Echo p1's properties to the console
Console.WriteLine("I have just deserialized the text above.");
Console.WriteLine("p1.age = " + p1.age);
Console.WriteLine("p2.name = " + p1.name);
Console.WriteLine("Press any key to close the test application.");
Console.ReadLine();
}
}
}
Happy Coding!