Converting Data Table / Dataset Into JSON String

JSON (Java Script Object Notation), is a light weight, easily understandable to read and write string. It is also easily parse-able by machine.

JSON is introduced on two structues

A collection (key/value pair)

And ordered list of values.

I have not covered this topic in detail. Detailed analysis is stated on http://www.json.org/.

I am presenting a helper function (in C#) for developers for fast parsing on datatable / dataset into JSON String, and access it on client-side.

public static string GetJSONString(DataTable Dt)

{

string[] StrDc = new string[Dt.Columns.Count];

string HeadStr = string.Empty;

for (int i = 0; i < Dt.Columns.Count; i++)

{

StrDc[i] = Dt.Columns[i].Caption;

HeadStr +=
"\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";

}

HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);

StringBuilder Sb = new StringBuilder();

Sb.Append("{\"" + Dt.TableName + "\" : [");

for (int i = 0; i < Dt.Rows.Count; i++)

{

string TempStr = HeadStr;

Sb.Append("{");

for (int j = 0; j < Dt.Columns.Count; j++)

{

TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString());

}

Sb.Append(TempStr +
"},");

}

Sb =
new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));

Sb.Append("]};");

return Sb.ToString();

}

Here, Dt is the datatable, and it returns JSON formatted string.

For detailed porcedure on how to access this string on client side, please refer to this link Exposing Webservices to Client-Side because I don't like to do task repetition.

Please donot forget to convert to JSON string to JSON Object using

var JObject = eval('(' + JSONString + ')');

in Javascript JObject have all characteristics of JSON object, through which you can Use JObject by iterrating or what so ever.

e.g., you can use your JObject as

for(var i = 0; i < JObject .Employees.length; i++)

{

var val1 = JObject.Employees[i].EmployeeID;

var val2 = JObject.Employees[i].NationalIDNumber;

var val3 = JObject.Employees[i].Title;

var val4 = JObject.Employees[i].BirthDate;

var val5 = JObject .Employees[i].HireDate ;

}

Please note that I am querieng data from AdventurWorksDB SQL Sample Database (Table: Employee).

I hope this article will be helpful for you.

Any Questions / Queries ??

Regards,

Naveed Akhtar

kick it on DotNetKicks.com

Published Tuesday, July 08, 2008 7:04 PM by NavaidAkhtar

Comments

# re: Converting Data Table / Dataset Into JSON String

Wednesday, July 09, 2008 4:10 PM by RichardD

This looks like a very fragile method. If you're using .NET 3.5 (or the MS AJAX 1.0 library), you already have the JavaScriptSerializer which does most of the work.

Unfortunately, the DataTable and DataSet objects aren't suitable for JSON serialization directly; you'll need to convert them first. To duplicate your results, you need to convert the DataSet to an IDictionary<string, IEnumerable<IDictionary<string, object>>>.

With LINQ, the code is fairly simple:

static object RowsToDictionary(this DataTable table)

{

   var columns = table.Columns.Cast<DataColumn>().ToArray();

   return table.Rows.Cast<DataRow>().Select(r => columns.ToDictionary(c => c.ColumnName, c => r[c]));

}

static Dictionary<string, object> ToDictionary(this DataTable table)

{

   return new Dictionary<string, object>

   {

       { table.TableName, table.RowsToDictionary() }

   };

}

static Dictionary<string, object> ToDictionary(this DataSet data)

{

   return data.Tables.Cast<DataTable>().ToDictionary(t => t.TableName, t => t.RowsToDictionary());

}

public static string GetJSONString(DataTable table)

{

   JavaScriptSerializer serializer = new JavaScriptSerializer();

   return serializer.Serialize(table.ToDictionary());

}

public static string GetJSONString(DataSet data)

{

   JavaScriptSerializer serializer = new JavaScriptSerializer();

   return serializer.Serialize(data.ToDictionary());

}

# re: Converting Data Table / Dataset Into JSON String

Thursday, July 10, 2008 6:56 AM by NavaidAkhtar

Hi RichardD

Thanks for your feedback and a wonderful suggestions, but your answer also contradicts your answer beceause, you stated that your solution works on .Net 3.5 or above then .Net 2.0. But My solution is for developers having .Net 2.0 or may be prior to that.

LINQ, JSonSerializer, are not supporting in Net 2.0 or prior versions.

Leave a Comment

(required) 
(required) 
(optional)
(required)