Serialize and DeSerialize objects to JSON using C#

Serializing objects to JSON using C#

In this blog, we will see how to Serialize and Deserialize the objects to JSON. JSON.NET. This library allows you to serialize and deserialize with a single line of code, directly to the objects you defined.  To do that we can use JsonConvert.SerializeObject() Method for serialization and JsonConvert.DeserializeObject() for Deserialize. The below code define how to use these methods from C# code.

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 System.Data.SqlClient;

using Newtonsoft.Json;

using System.Data;

using System.Web.Script.Services;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

        SelectMethod();

    }

    [WebMethod]   

    public static string SelectMethod()

    {

        SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=TestDB; User ID=sa; Password=Micr0s0ft");

        {

            SqlCommand cmd = new SqlCommand("select * from TestTable", con);

            {

                SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);

                DataTable dt = new DataTable();

                sqlDa.Fill(dt);

                string test = JsonConvert.SerializeObject(dt); // Serialization

                //JsonConvert.DeserializeObject(test);

                DataTable dtt = (DataTable)JsonConvert.DeserializeObject(test, dt.GetType());

                return test;

            }

        }

    }

}

 

Now set a breakpoint and check the serialization.

json.jpg


Deserialization

Now we want to convert a serialization string into object. The below code use JsonConvert.DeserializeObject() method.

DataTable dtt = (DataTable)JsonConvert.DeserializeObject(test, dt.GetType());