JSON Serialization Using Newtonsoft JSON Serialize

In today’s communication system JSON plays one very important role and we can say that day by day JSON is replacing XML, though XML has it’s own beauty and I hope JSON will never be an alternate of XML. In some situations however people are familiar with XML and they are using JSON now.

Think about an AJAX call from a client application, in the old days (not very old, even AJAX is a new concept) people used to use XML to talk with service-based applications like Web Services or WCF Services. But by the introduction of the Web API people began using JSON as a data encoding format.

That’s cool, JSON is lightweight and there is no un-necessary data using overhead bandwidth like as for XML. The Web API has a built-in capability to serialize the return value as JSON format but some situation exists (in another service or Page Method in the code behind of the WebForm) that the developer needs to serialize data in JSON format.

We have now reached our core topic, how to serialize data in JSON format. There are many ways to do it. The .NET class library has its own class to serialize JSON data and another good option is to use a JSON serialize library of third-party components. In this article we will use the Newtonsoft JSON serialization library to serialize JSON data.

At first download and install the Newtonsoft JSON serializer package using the NuGet package manager and you will see this reference in your current solution:

Newtonsoft JSON

Serialize Class object using Newtonsoft JSON serializer


In this example we will learn to serialize a class object into JSON format using the JsonConvert class. Here is the implementation of the client application.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="callAJAX.aspx.cs" Inherits="clientProject.callAJAX" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head id="Head1" runat="server">  
  5.     <script src="JQuery.js" type="text/javascript"></script>  
  6.     <script>  
  7.                $(document).ready(function () {  
  8.     $('#btn').click(function () {  
  9.         var name = $('#name').val();  
  10.         jQuery.ajax({  
  11.             url: 'callAJAX.aspx/GetData',  
  12.             type: "POST",  
  13.             dataType: "json",  
  14.             data: "{'name':'" + name + "'}",  
  15.             contentType: "application/json; charset=utf-8",  
  16.             success: function (data) {  
  17.                 alert(JSON.stringify(data));  
  18.             }  
  19.         });  
  20.     });  
  21. });  
  22.     </script>  
  23. </head>  
  24. <body>  
  25.     <input type="text" name="name" id="name" />  
  26.     <input type="button" name="btn1" id="btn" value="ClickMe" />  
  27. </body>  
  28. </html>  
We will now implement a GetData() function in code behind of the WebForm. Please note that we have included the Newtonsoft.Json namespace in our application and we are allowed to use the Jsonconverter class now. Here is the code implementation.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Web.Services;  
  8. using Newtonsoft.Json;  
  9. namespace clientProject  
  10. {  
  11.     public class person  
  12.     {  
  13.         public string name { getset; }  
  14.     }  
  15.     public partial class callAJAX : System.Web.UI.Page  
  16.     {  
  17.         protected void Page_Load(object sender, EventArgs e)  
  18.         {  
  19.         }  
  20.         [WebMethod()]  
  21.         public static string GetData(string name)  
  22.         {  
  23.             person p = new person();  
  24.             p.name = name;  
  25.             return JsonConvert.SerializeObject(p);  
  26.         }  
  27.     }  
  28. }  
The following is the output of the example above, we see that the data has come in JSON format.

JSON Format

Serialize List using Newtonsoft JSON serializer


A point to be noted here is that, using the Newtonsoft JSON serializer package, we can serialize almost every data type (both user defined and predefined) and in this example we will serialize a list of person classes. Have a look at the following example. 

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="callAJAX.aspx.cs" Inherits="clientProject.callAJAX" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head id="Head1" runat="server">  
  5.     <script src="JQuery.js" type="text/javascript"></script>  
  6.     <script>  
  7.                $(document).ready(function () {  
  8.     jQuery.ajax({  
  9.         url: 'callAJAX.aspx/GetData',  
  10.         type: "POST",  
  11.         dataType: "json",  
  12.         contentType: "application/json; charset=utf-8",  
  13.         success: function (data) {  
  14.             alert(JSON.stringify(data));  
  15.         }  
  16.     });  
  17. });  
  18.     </script>  
  19. </head>  
  20. </html>  
Here is the code behind implementation to serialize a list of person classes.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Web.Services;  
  8. using Newtonsoft.Json;  
  9. namespace clientProject  
  10. {  
  11.     public class person  
  12.     {  
  13.         public string name { getset; }  
  14.     }  
  15.     public partial class callAJAX : System.Web.UI.Page  
  16.     {  
  17.         protected void Page_Load(object sender, EventArgs e)  
  18.         {  
  19.         }  
  20.         [WebMethod()]  
  21.         public static string GetData()  
  22.         {  
  23.             List<person> p = new List<person>();  
  24.             person p1 = new person();  
  25.             p1.name = "Sourav";  
  26.             person p2 = new person();  
  27.             p2.name = "Ajay";  
  28.             p.Add(p1);  
  29.             p.Add(p2);  
  30.             return JsonConvert.SerializeObject(p);  
  31.         }  
  32.     }  
  33. }  
Here is the output of this example and we are getting data in JSON format rather than a List format.

data in JSON format

Conclusion

In this article we have learned to serialize any data to JSON format using the Newtonsoft JSON serializer. I hope you have understood the concept and will use this library in a JSON serialization scenario in your next application.


Similar Articles