3

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?

1

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

See this question about how to convert your JSON code into a DataSet object (which plays nicely with GridView objects).

From there, you can assign the DataSource property of your GridView to your converted DataSet and then run the DataBind() method.

I personally prefer to use code behind approach when actually rendering the data by using templates and the RowDataBound event to format my data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.