问题
I have a DataTable. When it's serialized into JSON with
Newtonsoft.Json.JsonConvert.SerializeObject(dataTable)
I get results in the following format:
[
{
"CLICK_KEY": 6254523744,
"WEB_SERVER_KEY": 291,
"PREV_CLICK_KEY": 0,
"NEXT_CLICK_KEY": 0,
"SESSION_KEY": 214981151,
*more key value pairs*
},
{
"CLICK_KEY": 6254523745,
"WEB_SERVER_KEY": 291,
"PREV_CLICK_KEY": 0,
"NEXT_CLICK_KEY": 0,
"SESSION_KEY": 214746780
*more key value pairs*
},
*many more objects (for each row)*
]
Since I have many columns and many rows, the resulting JSON is huge. This is mostly because column names are long and keep repeating for each row of data.
Is there a way to change settings of Json.Net so that the resulting JSON string is reduced in size? For instance, by formatting output as:
{
"NAMES": [
"CLICK_KEY",
"WEB_SERVER_KEY",
"PREV_CLICK_KEY",
"NEXT_CLICK_KEY",
"SESSION_KEY",
*more keys*
],
"VALUES": [
[6254523744, 291, 0, 0, 214981151, *more values*],
[6254523745, 291, 0, 0, 214746780, *more values*],
*many more arrays of values (for each row)*
]
}
I will not need to deserialize this back into a table or another object, so a "one-way" solution would work.
Thanks!
Update:
I followed advice from @spender & @TravisJ and transformed my DataTable
into another type for which Newtonsoft.Json.JsonConvert.SerializeObject() outputs what I need. Note how I start at DataSet
level so if it contains more than one DataTable
, it will include each one in the array.
var converted = from x in dataSet.Tables.Cast<DataTable>()
select new
{
NAMES = x.Columns.Cast<DataColumn>().Select(l => l.Caption),
VALUES = x.Rows.Cast<DataRow>().Select(l => l.ItemArray)
};
string jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(converted);
回答1:
You could just convert the datatable to the format you need using a linq projection:
Newtonsoft.Json.JsonConvert.SerializeObject(
dataTable.Select(
d => new {
Names = d.Columns.Select(c => c.ColumnName).ToArray(),
Values = d.Rows.Select(r => r.ToArray()).ToArray()
})
);
来源:https://stackoverflow.com/questions/16659560/formatting-output-of-newtonsoft-json-jsonconvert-serializeobjectdataset