How To Serialize An Object To JSON In Jquery Ajax




Here we consider how to Serialize An Object To JSON In Jquery Ajax. Lets start with one example here. Suppose we have an Ajax Call as shown below.

$(function(){
     $.ajax({
         url: 'PageName.aspx/MethodName',
         type: "POST",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function () {

         },
         error: function () {

         }
    })
})




For this ajax call, there are two input that needs to be serialized.

[WebMethod]
public static void MethodName(string key1, string key2)
{

}



So the above ajax request can be modified as follows.

$(function(){
     $.ajax({
         url: 'PageName.aspx/MethodName',
         type: "POST",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         data : JSON.stringify ({ key1: "YourValue1" , key2: "YourValue2" }),
         success: function () {

         },
         error: function () {

         }
    })
})




That's all, by using JSON.stringify, we can Serialize An Object To JSON. Now for converting a JSON string to object, use JSON.parse

var your_object = JSON.parse("jsontext");