Converting a Json string to C# object using JavaScriptSerializer

Gradually web development is shifting it’s focus to Client side programming day by day. Json is simply a Fat Free alternative to XML. Earlier XML was our commonly accepted data format across all the platforms, but JSON seems to be even more promising because of it’s light weight and familiar syntax (reminds me of .Net  object initializer).   Jquery on the other hand has become a standard which has excellent support with JSON format.

Let’s say we have a C# class Product.


class Product {

int ProductID;

string ProductName;

int CategoryID;

int SupplierID;

decimal UnitPrice;

}

JSON string example : We need to make sure our json string syntax is correct.  Class property names should be same to map it by default.

Here is the syntax

“{Property1 : ‘stringvalue’ , Property2 : ‘stringValue2’, Property3 : 123 }”

var jsonProductString = "{ ProductID :" + pid + ", ProductName :'" + pName + "',CategoryID :" + categoryId + ", SupplierID :" + supplierId + ", UnitPrice :" + unitPrice + "}";

Conversion to C# object: this is code is tested in .Net4.0.


System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

 var p = serializer.Deserialize<Product>(args);
// p is Product object initialized with Json string values.

Interesting part is after deserialization all the data types are easily mapped to Product class data types

Update:  There is a new serialization technique which performs even better for Json serialization. It is Json.Net library developed by James Newton King. it is available on codeplex.

Read more about Json.Net library on my Post on Json.Net library.
I hope it will be useful!!

Advertisements

About saxenapraveen

I work with Microsoft and have 12 years of experience in developing,designing and leading reliable and scalable solutions for cloud and device ready businesses.

Posted on February 24, 2012, in .NET, C#, Javascript, Jquery and tagged , , , , , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: