Geeks With Blogs

News Awarded Microsoft MVP C#.NET - 2007, 2008 and 2009


I am born in Bangladesh and currently live in Melbourne, Australia. I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net)and born in Bangladesh.
I am founder and Chief Executive Officer of
Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Co-founder and core developer of Pageflakes www.pageflakes.com.
Simplexhub, is on its mission to build a smart virtual community in Bangladesh and recently launched beta realestatebazaar.com.bd an ASP.NET MVC application written in C#.NET.


Some of My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET

Shahed Khan blog

Very recently I wrote an application where I had to deal with DataSet from a Web Service.

Please note, I have no control on the Web Service and I ended up writing a small function which converts DataTable to JSON.

I understand I haven't gain anything on the web traffic, but it surely simplified my JavaScript programming.


Let me go through what I did

Step 1.  Extract the XML Schema.
DataTable has two handy methods to extract Xml and Xml Schema. I extracted the Xml Schema to be able to generate a C# class using the xsd.exe.

    string path = "Your File Path";
    myDataTable.WriteXml(path);
    myDataTable.WriteXmlSchema(path);


Step 2. Generate C# Class using Xsd.exe that ships with the .NET Framework.

    C:\temp>xsd mydatatable.xsd /l:cs /c
    Microsoft (R) Xml Schemas/DataTypes support utility
    [Microsoft (R) .NET Framework, Version 2.0.50727.42]
    Copyright (C) Microsoft Corporation. All rights reserved.
    Writing file 'C:\temp\mydatatableclass.cs'.

 

Step 3. DataTable to Object conversion

The Web Service returns DataSet/ DataTable, and I want to transform all data that I I receive in the DataTable, to an instance of the class that I just generated in the above step.  Something like this:   

    private T DataTableToT<T>(DataTable dataTable, T obj)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            dataTable.WriteXml(ms);
            Type thetype = obj.GetType();
            XmlSerializer x = new XmlSerializer(thetype);
            ms.Position = 0;
            return (T)x.Deserialize(ms);           
        }
    }

The above method uses the WriteXml() to write the data of DataTable in to a MemoryStream, then using the XmlSerializer I deserialize the xml to a .NET object. Here is how we may use the this method:

    DataSet ds = WebService.GetDataSet();
    DataTable myDataTable = ds.Tables[0];
    MyDataTableClass obj = DataTableToT(myDataTable, new MyDataTableClass());


Step 4. Serialize .NET object to JSON

We have done the hard part above, now we have .NET object so we have all the flexibility as you can imagine. I found that there is a handful amount of libraries which can serialize .Net Objects to JSON string ie. JavaScriptSerializer, DataContractJsonSerializer, JSON.NET etc.

JavaScriptSerializer ships with System.Web.Extensions.dll and you can locate it under Namespace:  System.Web.Script.Serialization. The following method returns JSON from a .NET object using JavaScriptSerializer.

    private string GetJSONUsingJavaScriptSerializer<T>(T obj)
    {       
       JavaScriptSerializer serializer = new JavaScriptSerializer();
       string json =   serializer.Serialize(obj);
       return json;       
    }


DataContractJsonSerializer also does pretty much the same as above, it ships with .NET Framework 3.5 :  System.ServiceModel.Web.dll, and you can locate this under  Namespace:  System.Runtime.Serialization.Json, But we need to decorate the class with DataContract and DataMember attributes. Example

    [DataContract]
    class Order
    {
        [DataMember]
        public int OrderID { get; set; }
        [DataMember]
        public DateTime OrderDate { get; set; }
    }


and the following method can return a JSON string.

    private string GetJSONUsingDataContractJsonSerializer<T>(T obj)
    {
        using (MemoryStream ms = new MemoryStream())
        {           
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            serializer.WriteObject(ms, obj);           
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }


Conclusion

Here we have discussed how we can easily transform a DataTable to JSON. Sometimes we do not have enough control over the Web Service, or we may need to invoke a legacy Web Service that returns DataSet/ DataTable. In those scenarios sometimes converting DataTable to JSON comes very handy in AJAX programming. In the above example I have shown plain vanilla .NET methods, but we can even take it further and implement Extention methods to return JSON string. Scott has shown in his blog how to produce JSON using JavascriptSerializer. Here I show how we can do the same using DataContractJsonSerializer.

Example:

        public static string ToJSON<T>(this T obj)
        {
            using (MemoryStream ms = new MemoryStream())           
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(ms, obj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }           
        }

and then we will be able to use it like this on a order collection,

     string json = orders.ToJSON();


 

Hope this helps.

Posted on Saturday, March 22, 2008 5:31 PM | Back to top


Comments on this post: DataTable to JSON and ToJSON() Extension

# re: DataTable to JSON and ToJSON() Extension
Requesting Gravatar...
The instation of a serializer is an expensive process. You will get better performance if you create these lazily as follows:

private volatile static XmlSerializer x = new XmlSerializer(thetype);
Left by Barry Paterson on Mar 22, 2008 8:03 PM

# re: DataTable to JSON and ToJSON() Extension
Requesting Gravatar...
Hi Shahed,
Nice one :) How about using JayRock? I find it to be simpler.
Please check this:
http://kris.novogeek.net/post/2009/04/22/Converting-DataTable-to-JSON-using-JayRock.aspx
Left by Krishna on Apr 23, 2009 2:17 PM

# re: DataTable to JSON and ToJSON() Extension
Requesting Gravatar...
By using Jayrock.Json
You could convert almost any object into json string
string myJson = Jayrock.Json.Conversion.JsonConvert.ExportToString(anyObj);
Left by loihai on Apr 29, 2009 8:48 AM

# re: DataTable to JSON and ToJSON() Extension
Requesting Gravatar...
good convert almost any object into json string
string myJson = Jayrock
Left by ديكور منزل on Sep 17, 2009 6:37 AM

Your comment:
 (will show your gravatar)


Copyright © Shahed Khan | Powered by: GeeksWithBlogs.net | Join free