Search code examples
c#jsonjson.net

How to handle null/empty values in JsonConvert.DeserializeObject


I have the following code:

return (DataTable)JsonConvert.DeserializeObject(_data, (typeof(DataTable)));

Then, I tried:

var jsonSettings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
};

return (DataTable)JsonConvert.DeserializeObject<DataTable>(_data, jsonSettings);

The return line is throwing the error:

{"Error converting value \"\" to type 'System.Double'."}

Lots of solutions online suggesting creating custom Class with nullable types but this won't work for me. I can't expect the json to be in a certain format. I have no control over the column count, column type, or column names.


Solution

  • You can supply settings to JsonConvert.DeserializeObject to tell it how to handle null values, in this case, and much more:

    var settings = new JsonSerializerSettings
                        {
                            NullValueHandling = NullValueHandling.Ignore,
                            MissingMemberHandling = MissingMemberHandling.Ignore
                        };
    var jsonModel = JsonConvert.DeserializeObject<Customer>(jsonString, settings);