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.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="callAJAX.aspx.cs" Inherits="clientProject.callAJAX" %>

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <script src="JQuery.js" type="text/javascript"></script>

    <script>

               $(document).ready(function () {

    $('#btn').click(function () {

        var name = $('#name').val();

        jQuery.ajax({

            url: 'callAJAX.aspx/GetData',

            type: "POST",

            dataType: "json",

            data: "{'name':'" + name + "'}",

            contentType: "application/json; charset=utf-8",

            success: function (data) {

                alert(JSON.stringify(data));

            }

        });

    });

});

    </script>

</head>

<body>

    <input type="text" name="name" id="name" />

    <input type="button" name="btn1" id="btn" value="ClickMe" />

</body>

</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.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Services;

using Newtonsoft.Json;

 

namespace clientProject

{

    public class person

    {

        public string name { get; set; }

    }

    public partial class callAJAX : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

        }

       

        [WebMethod()]

        public static string GetData(string name)

        {

            person p = new person();

            p.name = name;

            return JsonConvert.SerializeObject(p);

        }

    }

}

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.
 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="callAJAX.aspx.cs" Inherits="clientProject.callAJAX" %>

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <script src="JQuery.js" type="text/javascript"></script>

    <script>

               $(document).ready(function () {

    jQuery.ajax({

        url: 'callAJAX.aspx/GetData',

        type: "POST",

        dataType: "json",

        contentType: "application/json; charset=utf-8",

        success: function (data) {

            alert(JSON.stringify(data));

        }

    });

});

    </script>

</head>

</html>
 
Here is the code behind implementation to serialize a list of person classes.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Services;

using Newtonsoft.Json;

 

namespace clientProject

{

    public class person

    {

        public string name { get; set; }

    }

    public partial class callAJAX : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

        }       

        [WebMethod()]

        public static string GetData()

        {

            List<person> p = new List<person>();

            person p1 = new person();

            p1.name = "Sourav";

            person p2 = new person();

            p2.name = "Ajay";

            p.Add(p1);

            p.Add(p2);

            return JsonConvert.SerializeObject(p);

        }

    }

}

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 serilization scenario in your next application.

Up Next
    Ebook Download
    View all
    Learn
    View all