<?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>Sun, 20 Nov 2011 01:44:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<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 [...]]]></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>Below is the solution.</p>
<table width="400" border="1" cellspacing="0" cellpadding="2">
<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 width="400" border="1" cellspacing="0" cellpadding="2">
<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;">"select user_name, active_indicator, create_date from users"</span>;
    <span style="color: blue;">string </span>connString = <span style="color: #a31515;">"database=db; server=localhost; user id=sa;"</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;">"mydt"</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" onclick="pageTracker._trackPageview('/outgoing/schotime.net/blog/index.php/2008/07/01/jquery-plugin-for-aspnet-ajax-jmsajax/?referer=');">jMsAjax plugin</a> as below will return the following JSON object.</p>
<table width="400" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td valign="top" width="400">
<pre class="code">$.jmsajax({
    type: <span style="color: #a31515;">"POST"</span>,
    url: <span style="color: #a31515;">"Default.aspx"</span>,
    method: <span style="color: #a31515;">"getTable"</span>,
    data: {},
    dataType: <span style="color: #a31515;">"msjson"</span>,
    success: <span style="color: blue;">function</span>(data) {
        $(outputDT(data.mydt)).appendTo(<span style="color: #a31515;">"body"</span>);
    }
});</pre>
</td>
</tr>
</tbody>
</table>
<p>Results (data):</p>
<table width="640" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td valign="top" width="638"><span style="font-size: 11px; font-family: courier new;">{&#8220;mydt&#8221;:{&#8220;user_name&#8221;:&#8221;000001&#8243;,&#8221;active_indicator&#8221;:&#8221;Y&#8221;,&#8221;create_date&#8221;:&#8221;\/Date(1170892765197)\/&#8221;}, {&#8220;user_name&#8221;:&#8221;000002&#8243;,&#8221;active_indicator&#8221;:&#8221;Y&#8221;,&#8221;create_date&#8221;:&#8221;\/Date(1170892765197)\/&#8221;}]}</span></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 width="400" border="1" cellspacing="0" cellpadding="2">
<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;">"&lt;tr&gt;"</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;">"&lt;td&gt;&lt;b&gt;"</span>+name+<span style="color: #a31515;">"&lt;/b&gt;&lt;/td&gt;"</span>);
    headers.push(<span style="color: #a31515;">"&lt;/tr&gt;"</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;">"&lt;tr&gt;"</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;">"&lt;td&gt;"</span>);
            rows.push(dataTable[row][name]);
            rows.push(<span style="color: #a31515;">"&lt;/td&gt;"</span>);
        }
        rows.push(<span style="color: #a31515;">"&lt;/tr&gt;"</span>);
    }            

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

    <span style="color: blue;">return </span>top + headers.join(<span style="color: #a31515;">""</span>) + rows.join(<span style="color: #a31515;">""</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,</p>
<p>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>

