BizTalk Utilities CV ,   Jobs ,   Code library
 
Go to the front page to continue learning about XML or select below:

Contents

ReBlogger Contents

Previous posts in XmlSerializer

 
 
Page 6057 of 21350

DataTable to JSON and ToJSON() Extension

Blogger : Geekswithblogs.net
All posts : All posts by Geekswithblogs.net
Category : XmlSerializer
Blogged date : 2008 Mar 23

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.


Read comments or post a reply to : DataTable to JSON and ToJSON() Extension
Page 6057 of 21350

Newest posts
 

    Email TopXML