<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Schotime.net &#187; Json</title>
	<atom:link href="http://schotime.net/blog/index.php/tag/json/feed/" rel="self" type="application/rss+xml" />
	<link>http://schotime.net/blog</link>
	<description>All Things .Net and Me</description>
	<lastBuildDate>Thu, 01 Jul 2010 14:42:28 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Dataset, Datatable to Json</title>
		<link>http://schotime.net/blog/index.php/2008/07/27/dataset-datatable-to-json/</link>
		<comments>http://schotime.net/blog/index.php/2008/07/27/dataset-datatable-to-json/#comments</comments>
		<pubDate>Sun, 27 Jul 2008 05:51:36 +0000</pubDate>
		<dc:creator>Schotime</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Json]]></category>

		<guid isPermaLink="false">http://schotime.net/blog/index.php/2008/07/27/dataset-datatable-to-json/</guid>
		<description><![CDATA[After my previous posts about returning data to the client as a JSON object, I decided to have a go at returning a generic Datatable/Dataset. This however is not as easy as simple returning a Datatable in your code behind method or web service. There is a solution though and here it is.
If you break [...]]]></description>
			<content:encoded><![CDATA[<p>After my previous posts about returning data to the client as a JSON object, I decided to have a go at returning a generic Datatable/Dataset. This however is not as easy as simple returning a Datatable in your code behind method or web service. There is a solution though and here it is.</p>
<p>If you break a Datatable down it is really only a List of Dictionary objects so that&#8217;s how we&#8217;ll approach this problem. This is compatible with .NET 2.0 and above, with the Ajax installed.</p>
<p>I&#8217;d like to acknowledge <a href="http://www.trinet.co.uk/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.trinet.co.uk/?referer=');">RichardD</a> for the idea.</p>
<p>Below is the solution.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">
<pre class="code"><span style="color: blue">using </span>System.Collections.Generic;
<span style="color: blue">using </span>System.Data;

<span style="color: blue">public static class </span><span style="color: #2b91af">JsonMethods
</span>{
    <span style="color: blue">private static </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;&gt;
        RowsToDictionary(<span style="color: #2b91af">DataTable </span>table)
    {
        <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;&gt; objs =
            <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;&gt;();
        <span style="color: blue">foreach </span>(<span style="color: #2b91af">DataRow </span>dr <span style="color: blue">in </span>table.Rows)
        {
            <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; drow = <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;();
            <span style="color: blue">for </span>(<span style="color: blue">int </span>i = 0; i &lt; table.Columns.Count; i++)
            {
                drow.Add(table.Columns[i].ColumnName, dr[i]);
            }
            objs.Add(drow);
        }

        <span style="color: blue">return </span>objs;
    }

    <span style="color: blue">public static </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; ToJson(<span style="color: #2b91af">DataTable </span>table)
    {
        <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; d = <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;();
        d.Add(table.TableName, RowsToDictionary(table));
        <span style="color: blue">return </span>d;
    }

    <span style="color: blue">public static </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; ToJson(<span style="color: #2b91af">DataSet </span>data)
    {
        <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; d = <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;();
        <span style="color: blue">foreach </span>(<span style="color: #2b91af">DataTable </span>table <span style="color: blue">in </span>data.Tables)
        {
            d.Add(table.TableName, RowsToDictionary(table));
        }
        <span style="color: blue">return </span>d;
    }
}</pre>
</td>
</tr>
</tbody>
</table>
<p>The static class JsonMethods exposes two public static methods and a private method. The public method ToJson() takes either a Dataset or a Datatable, and returns a Dictionary&lt;string,object&gt; object. The key to this class is the RowsToDictionary() method. </p>
<p>This method iterates through all the rows creating a dictionary entry for each column in the row using the column name as the key and storing the data value into the object. It then adds the Dictionary object to a List of Dictionary Objects and returns this to the ToJson() method. This Dictionary list is then added to another Dictionary object using the table name as the key. We&#8217;ll see how this all works together soon.</p>
<p>Lets have a look at the code behind now.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">
<pre class="code">[System.Web.Script.Services.<span style="color: #2b91af">ScriptMethod</span>(ResponseFormat = <span style="color: #2b91af">ResponseFormat</span>.Json)]
[System.Web.Services.<span style="color: #2b91af">WebMethod</span>]
<span style="color: blue">public static </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; getTable()
{
    <span style="color: blue">string </span>sql = <span style="color: #a31515">&quot;select user_name, active_indicator, create_date from users&quot;</span>;
    <span style="color: blue">string </span>connString = <span style="color: #a31515">&quot;database=db; server=localhost; user id=sa;&quot;</span>;

    <span style="color: blue">return </span><span style="color: #2b91af">JsonMethods</span>.ToJson(GetDataTable(sql, connString));
}

<span style="color: blue">private static </span><span style="color: #2b91af">DataTable </span>GetDataTable(<span style="color: blue">string </span>sql, <span style="color: blue">string </span>connString)
{
    <span style="color: blue">using </span>(<span style="color: #2b91af">SqlConnection </span>myConnection = <span style="color: blue">new </span><span style="color: #2b91af">SqlConnection</span>(connString))
    {
        <span style="color: blue">using </span>(<span style="color: #2b91af">SqlCommand </span>myCommand = <span style="color: blue">new </span><span style="color: #2b91af">SqlCommand</span>(sql, myConnection))
        {
            myConnection.Open();
            <span style="color: blue">using </span>(<span style="color: #2b91af">SqlDataReader </span>myReader = myCommand.ExecuteReader())
            {
                <span style="color: #2b91af">DataTable </span>myTable = <span style="color: blue">new </span><span style="color: #2b91af">DataTable</span>();
                myTable.TableName = <span style="color: #a31515">&quot;mydt&quot;</span>;
                myTable.Load(myReader);
                myConnection.Close();
                <span style="color: blue">return </span>myTable;
            }
        }
    }
}</pre>
</td>
</tr>
</tbody>
</table>
<p>So what I have above is two static methods. One is GetTable which is the one we will access from the client. The other is a generic method for loading a results set into a Datatable. Note how I have set the TableName property. You will see why soon.</p>
<p>So using the <a href="http://schotime.net/blog/index.php/2008/07/01/jquery-plugin-for-aspnet-ajax-jmsajax/" target="_blank">jMsAjax plugin</a> as below will return the following JSON object.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">
<pre class="code">$.jmsajax({
    type: <span style="color: #a31515">&quot;POST&quot;</span>,
    url: <span style="color: #a31515">&quot;Default.aspx&quot;</span>,
    method: <span style="color: #a31515">&quot;getTable&quot;</span>,
    data: {},
    dataType: <span style="color: #a31515">&quot;msjson&quot;</span>,
    success: <span style="color: blue">function</span>(data) {
        $(outputDT(data.mydt)).appendTo(<span style="color: #a31515">&quot;body&quot;</span>);
    }
});</pre>
</td>
</tr>
</tbody>
</table>
<p>Results (data):<br />
  </p>
<table cellspacing="0" cellpadding="2" width="640" border="1">
<tbody>
<tr>
<td valign="top" width="638">
<p><span style="font-size: 11px; font-family: courier new">{&quot;mydt&quot;:{&quot;user_name&quot;:&quot;000001&quot;,&quot;active_indicator&quot;:&quot;Y&quot;,&quot;create_date&quot;:&quot;\/Date(1170892765197)\/&quot;}, {&quot;user_name&quot;:&quot;000002&quot;,&quot;active_indicator&quot;:&quot;Y&quot;,&quot;create_date&quot;:&quot;\/Date(1170892765197)\/&quot;}]}</span> </p>
</td>
</tr>
</tbody>
</table>
<p>In the resulting data, the table name is the key to referencing the array of values. In this case we use &#8216;mydt&#8217; as the key. In the success function on the client request you may also notice an outputDT function. This is a little helper function which takes a JSON Datatable and returns a the results in a table. This is very useful for debugging. Here is the client side code.</p>
<table cellspacing="0" cellpadding="2" width="400" border="1">
<tbody>
<tr>
<td valign="top" width="400">
<pre class="code"><span style="color: blue">function </span>outputDT(dataTable)
{
    <span style="color: blue">var </span>headers = [];
    <span style="color: blue">var </span>rows = [];

    headers.push(<span style="color: #a31515">&quot;&lt;tr&gt;&quot;</span>);
    <span style="color: blue">for </span>(<span style="color: blue">var </span>name <span style="color: blue">in </span>dataTable[0])
        headers.push(<span style="color: #a31515">&quot;&lt;td&gt;&lt;b&gt;&quot;</span>+name+<span style="color: #a31515">&quot;&lt;/b&gt;&lt;/td&gt;&quot;</span>);
    headers.push(<span style="color: #a31515">&quot;&lt;/tr&gt;&quot;</span>);

    <span style="color: blue">for </span>(<span style="color: blue">var </span>row <span style="color: blue">in </span>dataTable)
    {
        rows.push(<span style="color: #a31515">&quot;&lt;tr&gt;&quot;</span>);
        <span style="color: blue">for </span>(<span style="color: blue">var </span>name <span style="color: blue">in </span>dataTable[row])
        {
            rows.push(<span style="color: #a31515">&quot;&lt;td&gt;&quot;</span>);
            rows.push(dataTable[row][name]);
            rows.push(<span style="color: #a31515">&quot;&lt;/td&gt;&quot;</span>);
        }
        rows.push(<span style="color: #a31515">&quot;&lt;/tr&gt;&quot;</span>);
    }            

    <span style="color: blue">var </span>top = <span style="color: #a31515">&quot;&lt;table border='1'&gt;&quot;</span>;
    <span style="color: blue">var </span>bottom = <span style="color: #a31515">&quot;&lt;/table&gt;&quot;</span>;  

    <span style="color: blue">return </span>top + headers.join(<span style="color: #a31515">&quot;&quot;</span>) + rows.join(<span style="color: #a31515">&quot;&quot;</span>) + bottom;
}</pre>
</td>
</tr>
</tbody>
</table>
<p>So as you can see, its now very easy to return a Datatable or Dataset as a JSON object ready for use on the client.</p>
<p>Hope this is as useful for you as it is for me.</p>
<p>Cheers,<br />
  <br />Schotime </p>
]]></content:encoded>
			<wfw:commentRss>http://schotime.net/blog/index.php/2008/07/27/dataset-datatable-to-json/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
