Tuesday 12 May 2015

How to Convert a DataTable into JSON formate in c# .NET ?

Here I pxplained how to convert a DataTable into JSON formate in c#.

 I used JavaScriptSerializer  to Serialize a List thats contains an object of Dictionary and this Dictionary contains of Column name as Index and Column value as Object. finally thsi List passed to JSSerializer.Serialize(ListObj) method


Surce Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.IO;
using System.Web;
using Newtonsoft.Json;

namespace ConsoleAppDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the DataTable.
            DataTable table =new DataTable();
            table = GetTable(table);
            //now Convert this table into JSON formate
            String json= GetJsonFormate(table);
            Console.WriteLine(json);
            Console.ReadKey();

           
        }

        static DataTable GetTable( DataTable table)
        {
          // Here I create a Employee DataTable with four columns.
            table.Columns.Add("EmpId", typeof(int));
            table.Columns.Add("EmpName", typeof(string));
            table.Columns.Add("Salary", typeof(int));
            table.Columns.Add("Company", typeof(string));

            // Here we add five DataRows.
            table.Rows.Add(101, "Ramu", 30000, "Kavin");
            table.Rows.Add(102, "Nanu", 35000, "Kavin");
            table.Rows.Add(103, "Sonu", 50000, "Kavin");
            table.Rows.Add(104, "Monu", 25000, "Kavin");
            table.Rows.Add(105, "Salu", 37000, "Kavin");
            return table;
        }
         static string GetJsonFormate(DataTable dt)
        {
            // Create an instance of JavaScript Serializer
            System.Web.Script.Serialization.JavaScriptSerializer JSSerializer = new
            System.Web.Script.Serialization.JavaScriptSerializer();

            // Create an instance of List thats contains an Object of Dictionary.
            List<Dictionary<string, object>> DtRows =
              new List<Dictionary<string, object>>();
            Dictionary<string, object> newrow = null;

            //Code to loop each row in the datatable and add it to the dictionary object
            foreach (DataRow drow in dt.Rows)
            {
                newrow = new Dictionary<string, object>();
                // Loop for each column
                foreach (DataColumn col in dt.Columns)
                {
                    newrow.Add(col.ColumnName.Trim(), drow[col]);
                }
                DtRows.Add(newrow);
            }

            //Serialising the dictionary object to produce json output
            JSSerializer.MaxJsonLength = Int32.MaxValue;

            return JSSerializer.Serialize(DtRows);
        }
    }

}



Output:-




How to convert JSON String into XML Document in c# .NET?

Here I expalined JSON and XML in briefly because this post  is how to convert JSON into XMl Doc

Whta is JSON:-

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.

Example :-

       var jason = {
                     "age" : "24",
                     "hometown" : "Missoula, MT",
                     "gender" : "male"

                   };

What si XML :-
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format which is both human-readable and machine-readable.

Example:-

<?xml version="1.0" encoding="UTF-8" ?>
<Emp Id>rps101</Emp Id>
<EmpName>Rampal</EmpName>
<EmpDOB>12-05-2015</EmpDOB>
<Salary>50000</Salary>
<Designation>Developer</Designation>


Now here I worte how to convert JSON string into XMl Document.

Source code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
using Newtonsoft.Json;

namespace ConsoleAppDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // sample json string
            String Json = "{\"Name\": \"Rampal\", \"Gender\": \"Male\",
            \"EmailId\": \"rphbti640@gmail.com\", \"MobileNo\": \"8861447949\", 
            \"City\": \"Bangluru\", \"Country\": \"India\"}";

            // Pass the json string to below method
            string smlDoc = ConvertJsonToXMLDoc(Json);
            Console.WriteLine(smlDoc);
            Console.ReadKey();

           
        }


        public static string ConvertJsonToXMLDoc(string jsondata)
        {
            string ResponseXMLData = string.Empty;
            // use the method DeserializeXmlNode abailabe in Newtonsoft.Json namespace
            XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsondata, "DocumentElement");
            // Create an instance of string writer class
            StringWriter sw = new StringWriter();
            // Create an instance of XML writer class
            XmlTextWriter xw = new XmlTextWriter(sw);
            // set the indented formate
            xw.Formatting = System.Xml.Formatting.Indented;
            // write as XML Doc
            doc.WriteTo(xw);
            return sw.ToString();
        }
    }

}

Output:-