Convert Javascript object into Json string<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Convert Javascript object into Json string

Posted on: March 4, 2013

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:

1public class MyClass {
2 int a;
3 int b;

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

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

You can use JQuery to send Ajax:

2 url: 'MyController/MyAction',
3 contentType: "application/json; charset=utf-8",
4 type: "POST",
5 data: JSON.stringify(xyz),
6 dataType: "json",
7 success: function (data) {
8 //...
9 }, error: function () {
10 //...
11 }

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.

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