JavaScript JSON Encode/Decode with Asp.Net Sample Code

In this article, we'll discuss how to Encode and Decode JavaScript JSON arrays when passing it from client to server side and vice versa using Asp.Net WebMethods.
We encode JavaScript object into JSON when we need to pass it from client side to server side. Decoding is done on the server side, so that the JavaScript object can be converted  into a C# class object. Consider for instance that we need to collect a few details about an employee and pass it to the server side to a web method.

Sending JSON from client to server  

First, we'll need to create a JavaScript function for the Employee as shown below:

After we have collected the employee details we'll create an instance of the Employee and pass this object over to the C# web method. Here is our C# web method.

As you can see the C# code also has a class quite similar to the JavaScript function. It's required in order to decode the JSON object passed from client side. We'll we calling the web method from client side using jQuery AJAX.
Given below is the jQuery Ajax code, about how to call the web method and pass the JSON data as parameter to C# web method.

The above code is pretty much self explanatory. We have created an instance of the Employee JavaScript function and passed in as parameter to the web method.
Two most common errors that I have encountered while trying to establish this web method are :

which occurs when the JSON that you are passing doesn't have the same parameter name as per the C# web method. Basically it means, if the web method is expecting a parameter called empData as the case is here, then the data passed from the jQuery AJAX should have the same parameter as

Another error which occurred was :

If you get this error then most probably, you are having the wrong web method name or else as was in my case the web method wasn't declared static.

Now when the data is passed as JSON object it's automatically decoded at the server side.

Sending JSON from server to client 

When sending data from server to client, we'll pass data as C# object from the web method as shown below:

In order to decode the JSON response to JavaScript object we'll make use of JSON.parse as shown below:

Things to note above are that we have used JavaScript serializer to serialize data from C# Object to proper JSON in the web method.

Ending Note 

In this article, we discussed and saw how to encode and decode JavaScript JSON both on server side and client side. Using the above code I have created a sample app which show the process of encoding and decoding the JSON. The code is available at GitHub. For a bit more info on JavaScript JSON have a look at the JavaScript JSON Array article.