Category Archives: Javascript

Json.Net – serialization and deserialization APIs for Json format

Json has emerged as a new favorite data format to be sent over the wire. It is a thinner alternative to XML data format. In any integration project conversion of different data formats is the back bone of data communication. like XML Json is also compatible to any platform and easily convertible to native data types.

What is Json.Net?    It is a portable class library developed by James Newton King which helps you serialize and deserialize Json strings to .Net objects.  Once you include this library in your project you can use it’s built – in classes like  JsonConvert to serialize and deserialize objects. You can also use its Linq to Json APIs which is really helpful and will remind you of  Linq to XML.

Where do i get it from?   Download it from CodePlex.   Latest version is Json.Net 4.5. You can install it using Nuget package manager from Visual studio (10 onwards). I would recommend you to start using Nuget if you don’t have it already.

Why Json.Net?    Nobody is going to start using any new library just because it is new and sounds cool. Right?

In .Net paradigm, We already have few alternatives to serialize/deserialize json objects apart from new Json.Net.

1)      DataContract serialization                   2)  JavaScript Serialization

to read more about JavascriptSerializer for Json serialization please read my post on  JavascriptSerializer for Json

Hence, main reason why should you choose Json.Net over DataContract serializer and JavaScript Serializer   is its performance and features it provides.  There is a very useful feature comparison done among three serialization techniques . Check it out on Json.Net features comparison

In short below are the main features it provides. 

  1. Flexible JSON serializer for converting between .NET objects and JSON
  2. LINQ to JSON for manually reading and writing JSON
  3. High performance, faster than .NET’s built-in JSON serializers
  4. Write indented, easy to read JSON
  5. Convert JSON to and from XML
  6. Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone

How Json.Net can be used?       finally some code 🙂

Step 1. Download  it from CodePlex. or preferably install it using Nuget Package manager.

Step 2. Make sure your project has Newtonsoft.Json dll in your bin folder.

here, Product is a C# type.

public class Product
 {
public string Name { get; set; }
public DateTime ExpiryDate { get; set; }
public decimal Price { get; set; }
public string[] Sizes { get; set; }
 }

Converting a json string to C# product object.


public Product JsonToProductObject(string jsonString)
 {
var deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonString);
return deserializedProduct;
 }

Converting product object to json fromat string.

public string ProductObjectToJson(Product product)
 {
 string json =JsonConvert.SerializeObject</strong>(product);
 return json;
 }

Linq to Json: There are instances when we do not need to serialize the objects just want to read few properties of an object or json string. Just Like Linq to XML Json.Net library also provides you the awesome capability of querying the json objects using Linq.

Below code is taken from the James.NewtonKing official website. Beauty of the code is to have the same declarative syntax that Linq users are so fond of.

List<Post> posts = GetPosts();
JObject rss =
new JObject(
new JProperty("channel",
new JObject(
new JProperty("title", "James Newton-King"),
new JProperty("link", "http://james.newtonking.com"),
new JProperty("description", "James Newton-King's blog."),
new JProperty("item",
new JArray(
from p in posts
orderby p.Title
select new JObject(
new JProperty("title", p.Title),
new JProperty("description", p.Description),
new JProperty("link", p.Link),
new JProperty("category",
new JArray(
from c in p.Categories
select new JValue(c)))))))));
// here is the output which is a json string
//{
//  "channel": {
//    "title": "James Newton-King",
//    "link": "http://james.newtonking.com",
//    "description": "James Newton-King's blog.",
//    "item": [
//      {
//        "title": "Json.NET 1.3 + New license + Now on CodePlex",
//        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
//        "link": "http://james.newtonking.com/projects/json-net.aspx",
//        "category": [
//          "Json.NET",
//          "CodePlex"
//        ]
//      },
//      {
//        "title": "LINQ to JSON beta",
//        "description": "Annoucing LINQ to JSON",
//        "link": "http://james.newtonking.com/projects/json-net.aspx",
//        "category": [
//          "Json.NET",
//          "LINQ"
//        ]
//      }
//    ]
//  }
//}
// Now we can query to get
var categories =  from c in rss.PropertyValue<JObject>("channel")                                                          .PropertyValue<JArray>("item")                                                                            .Children<JObject>()                                                                                      .PropertyValues<JArray>("category")                                                                       .Children<string>()                                                                                       group c by c into g                                                                                       orderby g.Count() descending                                                                              select new { Category = g.Key, Count = g.Count() };
foreach (var c in categories)                                                                             {
Console.WriteLine(c.Category + " - Count: " + c.Count);                                                  }
// below is the output
//Json.NET - Count: 2
//LINQ - Count: 1
//CodePlex - Count: 1

To understand the Json.Net library in detail, you can refer to the official Json.Net classes and APIs reference.

James Newton King had really made our lives easy with this cool library which is not only new but performs great when compared to existing serialization techniques. Hats off to him 🙂

Note: Examples and features are cited from the original json.Net website http://james.newtonking.com/

Advertisements

Jquery Modal dialog as Confirm in Asp.Net webforms

I love Jquery! it made me friends with client side scripting. Earlier it used to haunt me all the time.

If we have a button on a webform which should confirm the user action on click like a Delete button Jquery provides
Javascript methods:

<script type="text/javascript">
 $(document).ready(function () {
// this method opens a div with id="dialogContent" as a modal dialog box with Yes and No buttons.

$('#dialogContent').dialog({

autoOpen: false,
modal: true,
 bgiframe: true,
 title: "Confirm your action",
 width:200,
 height: 200
 });

});

// this method is called when Delete button is clicked.
function rowAction(uniqueName) {

$('#dialogContent').dialog('option', 'buttons',
 {
 "Yes": function () {
 __doPostBack(uniqueName, '');
 $(this).dialog("close");
 },
 "No": function () { $(this).dialog("close"); }
 });

$('#dialogContent').dialog('open');

return false;
 }
 </script>

.aspx code:


<asp:Button ID="btnDelete" runat="server" CommandArgument='<%# Eval("ProductID") %>'
Text="Edit" OnClick="btnDelete_Click" OnClientClick="javascript:return rowAction(this.name);" />

<div id="dialogContent">
Are you sure?

</div>

Code behind :


protected void Page_Load(object sender, EventArgs e)
 {

// register the postback reference. specify the control we are forcing to postback.

ClientScript.GetPostBackEventReference(btnDelete, string.Empty);
 }

// this event is fired when user presses <strong>Yes</strong> from Confirm Modal dialog.

protected void btnDelete_Click(object sender, EventArgs e)
 {
Button b = sender as Button;
if (b != null)
{
// do your actions here
}
 }

This way we get Jquery modal confirm box on a button click. once you press Yes we use our old friend javascript method __doPostBack(controlName, ”) to continue server side execution.

Please note that in __doPostback method second parameter is empty string,  If you need to pass some arguments while enforcing a postback. convert it to a Json string and pass it to code behind. You can convert this json string to C# object using Javascript serializer. 
Please refer to my article on json string to C# coversion http://wp.me/p1hH3Q-2E

I hope it is useful!

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.

Jquery event binding – jquery live api

Hi All,

Recently i faced an issue while developing a Asp.Net MVC3.0 application. On a link click i was trying to add new html to the existing DOM. For example on click of a link i was adding some new html tags to the existent DOM. Here is the code i wrote to make an ajax call on link click.


$(".editanchor").click(function () {

$.ajax({
// set the attributes and call an action method
});
});

It all worked fine but strangely when i click the link next time nothing happens. Then i realized the mistake i made while binding the click event to a handler.

As per jquery documentation Live() method should be used to bind the event to a callback if we are modifying the DOM structure during our page reload (partial or full) so that it would retain the binding next time you click the link.

Live(event, handler) : Attaches an event handler for all elements which match the current selector, now and in the future.

so the correct way to bind an event to a handler in such condition would be

$(".editanchor").live('click', function () {

$.ajax({
// set the attributes and call an action method
});
});

There are few performance considerations we should be aware of

  • Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  • jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.

EDIT: Here is the updated comparison of various flavors of binding an event.

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

I hope it helps.