Lara Lara - 4 months ago 14
JSON Question

How to format data while adding in generic List

I am trying to add all the data from

DataTable
into
List<string> dataFromDataTable = new List<string>();
for which I have written a c# code. later On I need to convert it into Json.

Here is the code.

List<string> dataFromDataTable = new List<string>();

for (int r = 0; r < employees.Rows.Count; r++)
{
dataFromDataTable.Add("{".ToString());
for (int c = 0; c < employees.Columns.Count; c++)
{
dataFromDataTable.Add(employees.Rows[r][c].ToString());
}
dataFromDataTable.Add("}".ToString());
}


and here is my json code.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(sample);


As of Now I am getting json like.

["John Doe","Fresno","Billy","Fresno","Tom","Kern","King Smith","Kings"]


whereas I need it like

["John Doe","Fresno"],["Billy","Fresno"],["Tom","Kern"],["King Smith","Kings"]]


How to di it.Thanks

Answer
var data = employees.AsEnumerable().Select(x => x.ItemArray).ToList();
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);

hope this helps