I am trying to serialise a DataSet (working with an old codebase and have to use a DataSet in this instance). I want to slim down the resulting JSON and remove null values and defaults (0 for int, false for bool). The following code does not exclude the int value in row 0 or the bool value in row 1, does anyone have any suggestions for how I can get this to work?
var dataSet = new DataSet();
dataSet.Tables.Add("MyTable");
dataSet.Tables[0].Columns.Add("StringValue", typeof(string));
dataSet.Tables[0].Columns.Add("IntValue", typeof(int));
dataSet.Tables[0].Columns.Add("BoolValue", typeof(bool));
var row = dataSet.Tables[0].NewRow();
row["StringValue"] = "Hello";
row["IntValue"] = 0;
row["BoolValue"] = true;
dataSet.Tables[0].Rows.Add(row);
row = dataSet.Tables[0].NewRow();
row["StringValue"] = null;
row["IntValue"] = 123;
row["BoolValue"] = false;
dataSet.Tables[0].Rows.Add(row);
var settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
Formatting = Formatting.Indented
};
Console.WriteLine(JsonConvert.SerializeObject(dataSet, settings));
/*OUTPUT:
{
"MyTable": [
{
"StringValue": "Hello",
"IntValue": 0,
"BoolValue": true
},
{
"IntValue": 123,
"BoolValue": false
}
]
}
*/
DataRow.IsNull(i) == true. A row with default value will haveDataRow.IsNull(i) == falseand `DataRow[i] returning a boxed default value. If you skip default values when serializing (especially for value types) you will lose that distinction.