I'm using the Newtonsoft Json Converter to serialize and deserialize objects and it works great for my program.
But if any of the values stored within the object are null/empty, they are serialized as {}
, unable to be deserialized, and my program stops.
For example, if I deserialize the following code, everything works great:
{
"Thing1": 2,
"Thing2": false,
"Thing3": "string",
"Thing4": "2017-10-28T14:04:24.74"
}
But if I try to deserialize the following code:
{
"Thing1": {},
"Thing2": false,
"Thing3": "",
"Thing4": {}
}
Thing1 and Thing4 will both cause problems during deserialization.
Not sure if this could be related to the way I am reading from my database to serialize:
var r = Serialize(myReader);
string json = JsonConvert.SerializeObject(r,
Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
public IEnumerable<Dictionary<string, object>> Serialize(SqlDataReader reader)
{
var results = new List<Dictionary<string, object>>();
var cols = new List<string>();
for (var i = 0; i < reader.FieldCount; i++)
cols.Add(reader.GetName(i));
while (reader.Read())
results.Add(SerializeRow(cols, reader));
return results;
}
private Dictionary<string, object> SerializeRow(IEnumerable<string> cols,
SqlDataReader reader)
{
var result = new Dictionary<string, object>();
foreach (var col in cols)
result.Add(col, reader[col]);
return result;
}
I've used:
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }
Within my deserializer:
BlankObject blnkObj = JsonConvert.DeserializeObject<BlankObject>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });