Introduction
This article demonstrates how to serialize and deserialize CLR objects for web-based applications. This article starts with an introduction to the System.Web.Script.Serialization.JavaScriptSerializer class. After that, a small code snippet is given for it and where exactly this approach fits into the web-based application
System.Object
System.Web.Script.Serialization.JavaScriptSerializer
Namespace
System.Web.Script.Serialization
Assembly
System.Web.Extensions (in System.Web.Extensions.dll)
Provides serialization and deserialization functionality for AJAX-enabled applications.
Creating CLR object
A plain CLS object, which has a few classes, attributes, and necessary methods as shown below,
class Person {
public string firstName, lastName, Designation;
public ushort age;
public string[] technologies;
public Address personAddress;
public override string ToString() {
base.ToString();
return string.Format(@ "Name: {0} {1}
Designation: {
2
}
Age: {
3
}
Skills: {
4
}
Address: {
5
} {
6
}, {
7
}
",
this.firstName, this.lastName, this.Designation, this.age, string.Join(",", this.technologies), this.personAddress.addressLine, this.personAddress.city, this.personAddress.country);
}
}
class Address {
public string addressLine, city, country;
}
Initiating and printing the CLR object to the console,
Person I = new Person();
I.firstName = "Adil";
I.lastName = "Ansari";
I.Designation = "Consultant";
I.age = 25;
Address personAddres = new Address() {
addressLine = "Vikhroli LBS West",
city = "Mumbai", country = "IN"
};
I.personAddress = personAddres;
I.technologies = new string[] {
".Net",
"SQL",
"SharePoint"
};
// Entity to string
Console.WriteLine("Entity:" + Environment.NewLine + I);
Console.ReadLine();
Output to the console
Serialization and Deserialization
Now to serialize and deserialize the CLR and JSON, a class JavaScriptSerializer needs to be initiated and its instance method will be used to do so, as listed below:
-
public string Serialize(Object obj)
Converts an object to a JSON string.
-
public T Deserialize<T>(string input)
Converts the specified JSON string to an object of type T.
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string serializedPerson = jsSerializer.Serialize(I);
// Serialized entity string
Console.WriteLine("Entity to JSON:" + Environment.NewLine + serializedPerson);
// Deserialized entity back to CLR object
Person Same = jsSerializer.Deserialize < Person > (serializedPerson);
Console.WriteLine("Back to Entity:" + Environment.NewLine + Same);
Summary
In this article, I discussed how to serialize and deserialize a CLR object to and from JSON using C# with an example. Instead of using any third-party DLLs for this purpose, we can have the native .Net capabilities available to us.
Reference
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx