Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Convert Javascript object into Json string

Posted on: 2013-03-04

When developing Javascript intensively at some point you may want to save the object. To save your Javascript object, you need to send it back to the server. Sometime, you may be able to send the object directly by using Javascript's Ajax functionality and use the converted object with Asp.Net MVC, other time, you may want to do it manually, so sending the object into a string and to deserialize into C# class.

The first approach is the simplest for simple object that you have the same meta structure into your C# class and Javascript object. For example, if you have a C# class that looks like this:

public class MyClass { 
   int a; 
   int b; 
} 

You would need to send from Javascript an object where Asp.Net MVC could map:

var xyz = {a=1,b=2}; 

You can use JQuery to send Ajax:

$.ajax({ 
  url: 'MyController/MyAction', 
  contentType: "application/json; charset=utf-8", 
  type: "POST", 
  data: JSON.stringify(xyz), 
  dataType: "json", 
  success: function (data) { 
    //... 
    }, error: function () { 
    //... 
  } 
}); 

As you can see, we pass the data information using JSON.stringify() which send the object serialized into a string format. The contentType property indicates in which format the data is sent, meanwhile the property dataType is how to data received back (in the success, error, complete function).

When the function return the data, this one is in a string format. If the desired return is Json, like the example above by specifying that the dataType is "json", we need to deserialize the string into Javascript object. JQuery provides the method jQuery.parseJSON(). This JQuery function calls the native 'window.JSON.parse()', if the function doesn't exist for the browser, it falls back to the eval function.

success: function (data) { 
  var obj = jQuery.parseJSON(data); 
}