NG.
NG.

Reputation: 6043

Convert data table to json

I have a data table in c# having content like :

firstName lastName email                   password
Alpha     Tango    [email protected]   123
Charle    Tango    [email protected] 456

I need to convert this datatable into json with below format.

{
    "columns": [ 
      "firstName", 
      "lastName", 
      "email", 
      "password",
    ],
    "rows": [
      [
        "Alpha",
        "Tango",
        "[email protected]",
        "123"
      ],
      [
        "Charle",
        "Tango",
        "[email protected]",
        "456"
      ]
    ]
}

I could get the rows converted into json array of arrays via JsonConvert.SerializeObject(dt1.AsEnumerable().Select(r => r.ItemArray)) but I am unable to get the entire json(having rows and columns). Any pointers will be highly appreciated.

Upvotes: 0

Views: 174

Answers (1)

Jcl
Jcl

Reputation: 28272

Something like this should work:

JsonConvert.SerializeObject(new {
   columns = dt1.Columns.Cast<DataColumn>().Select(x => x.ColumnName),
   rows = dt1.AsEnumerable().Select(r => r.ItemArray),
});

I've made a simple fiddle: https://dotnetfiddle.net/T5Gs8l

The result seems to be exactly what you are expecting:

{
  "columns": [
    "firstName",
    "lastName",
    "email",
    "password"
  ],
  "rows": [
    [
      "Alpha",
      "Tango",
      "[email protected]",
      "123"
    ],
    [
      "Charlie",
      "Tango",
      "[email protected]",
      "456"
    ]
  ]
}

Note that you lose the type information, so if your columns might be of varied datatypes, deserializing the object back to the same datatable might be tricky (you may need to infer the column types from the values).

I'd probably store more information on the columns if I was to deserialize it.

Upvotes: 3

Related Questions