C# – convert and bind JSON to asp.net gridview

asp.netcgridviewjsonweb

I have the following JSON

[{"time":"11:28","message":"user1: hi"},{"time":"11:28","message":"user2: hi to you"}] 

it was very easy to serialize from a database table using C#.
i used the following function to serialize

public String ConvertDataTableTojSonString(DataTable dataTable)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer =
           new System.Web.Script.Serialization.JavaScriptSerializer();

    List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();

    Dictionary<String, Object> row;

    foreach (DataRow dr in dataTable.Rows)
    {
        row = new Dictionary<String, Object>();
        foreach (DataColumn col in dataTable.Columns)
        {
            row.Add(col.ColumnName, dr[col]);
        }
        tableRows.Add(row);
    }
    return serializer.Serialize(tableRows);
}

i thought it might be some error in the JSON it self, but i tested it in http://jsonlint.org/ and it was valid
However i tried and searched a lot to convert it back to any format that can bind to asp.net gridview. any ideas?

Best Answer

I'd solve it like this:

First Step: Download JSON.net

Second Step:

in your CS page

using Newtonsoft.Json;

public DataTable DerializeDataTable()
{       
    string json = data; //"data" should contain your JSON 
    var table = JsonConvert.DeserializeObject<DataTable>(json);
    return table;
}

now use the function as a datasource to your gridview

protected void btn1_Click(object sender, EventArgs e)
{
GridView1.DataSource = DerializeDataTable();
GridView1.DataBind();
}

hope this helps