- I want to get records from database into a
DataTable
. - Then convert the
DataTable
into a JSON object. - Return the JSON object to my JavaScript function.
I use this code by calling:
string result = JsonConvert.SerializeObject(DatatableToDictionary(queryResult, "Title"), Newtonsoft.Json.Formatting.Indented);
To convert a DataTable to JSON, it works correctly and return the following:
{
"1": {
"viewCount": 703,
"clickCount": 98
},
"2": {
"viewCount": 509,
"clickCount": 85
},
"3": {
"viewCount": 578,
"clickCount": 86
},
"4": {
"viewCount": 737,
"clickCount": 108
},
"5": {
"viewCount": 769,
"clickCount": 130
}
}
But I would like it to return the following:
{"records":[
{
"Title": 1,
"viewCount": 703,
"clickCount": 98
},
{
"Title": 2,
"viewCount": 509,
"clickCount": 85
},
{
"Title": 3,
"viewCount": 578,
"clickCount": 86
},
{
"Title": 4,
"viewCount": 737,
"clickCount": 108
},
{
"Title": 5,
"viewCount": 769,
"clickCount": 130
}
]}
How can I do this?
I have simple function to convert datatable to json string.
I have used Newtonsoft to generate string. I don't use Newtonsoft to totaly serialize Datatable. Be careful about this.
Maybe this can be useful.
To access the convert datatable value in Json method follow the below steps:
With Cinchoo ETL - an open source library, you can export DataTable to JSON easily with few lines of code
Output:
Convert datatable to JSON using C#.net
An alternative way without using javascript serializer:
Pass the datable to this method it would return json String.