Blog Archives

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!!

Jquery – Calculate number of days between two dates.

This is a very common requirement we get almost in every project that’s why It is really helpful to keep it handy.


function calculateDifference() {
var startDate = $("#start_date").val();

if (startDate == “”) {
alert(“Enter start date”);
return;
}
var endDate = $(“#end_date”).val();
if (endDate == “”) {
alert(“Enter end date”);
return;
}

var startDateSplit = startDate.split(“/”);
var endDateSplit = endDate.split(“/”);

var stDate = new Date(startDateSplit[2], startDateSplit[0] – 1, startDateSplit[1]);
var enDate = new Date(endDateSplit[2], endDateSplit[0] – 1, endDateSplit[1]);

var difference = (enDate.getTime() – stDate.getTime()) / (1000 * 60 * 60 * 24);

$(“#date_difference”).val(difference);
}

I hope it helps.