.comment-link {margin-left:.6em;}

.code

.. Hello Earthling .. \o/ :)

Convert DataTable to JSON in C#
Monday, September 05, 2011

A generic code to convert your C# DataTable to JSON:



  string makejsonoftable(DataTable table, makejson e)
  {
    StringBuilder sb = new StringBuilder();
    foreach (DataRow dr in table.Rows)
    {
      if (sb.Length != 0)
        sb.Append(",");
      sb.Append("{");
      StringBuilder sb2 = new StringBuilder();
      foreach (DataColumn col in table.Columns)
      {
        string fieldname = col.ColumnName;
        string fieldvalue = dr[fieldname].ToString();
        if (sb2.Length != 0)
          sb2.Append(",");
        sb2.Append(string.Format("{0}:\"{1}\"", fieldname, fieldvalue));


      }
      sb.Append(sb2.ToString());
      sb.Append("}");


    }
    if (e == makejson.e_with_square_brackets)
    {
      sb.Insert(0, "[");
      sb.Append("]");
    }
    return sb.ToString();


  }

and I added this enum:

  enum makejson
  {
    e_without_square_brackets,
    e_with_square_brackets
  }

because you wont need the square brackets in case you are calling this function again for some nested object definition, for example like:
[{name:{name1:"ab",name2:"cd"},id:9}]

resulting json for one of my data query looked like this:

[{village_name:"Lourba leten",school_name:"EB 1.2 Nazare Gumer",village_id:"4030301",school_id:"525",classroom_id:"1893",location_name:"Seluk tan",location_id:"9"},{village_name:"",school_name:"",village_id:"",school_id:"",classroom_id:"1905",location_name:"Seluk tan",location_id:"9"}]

say you requested this through an ajax call, you can call a:
var jsondatastructure = eval (yourResponseText);
in case of the above sample result the "jsondatastructure" will have a jsondatastructure.length set to 2.




Comments:
very nice. Thanks.

Take a look into this article http://www.etechpulse.com/2012/09/convert-datatable-to-json-in-aspnet.html
 
Post a Comment

Links to this post:

Create a Link



<< Home



Blogs:

MSDN Blogs
Joel Pobar
Don Syme

Friends:
Adeel
Aqeel
#Fahad
Haroon
Omer
Muhammad Ali
Lahore Food Blog

Links:
Rotor
CodeGuru
Mozilla
OpenSourceNokia
Tech Blog

Languages:
IronPython
F#

Archives

June 2004   July 2004   August 2004   September 2004   October 2004   November 2004   December 2004   February 2005   April 2005   June 2005   July 2005   September 2005   October 2005   November 2005   June 2007   December 2007   January 2008   March 2008   April 2008   June 2008   October 2008   February 2009   May 2009   June 2009   July 2009   August 2009   March 2011   June 2011   July 2011   September 2011   October 2011   November 2011   December 2012   May 2013   October 2013   May 2014   March 2015   July 2015   August 2015   December 2015   March 2016   July 2016   October 2016   November 2016  

This page is powered by Blogger. Isn't yours?