How to handle null/empty values in JsonConvert.DeserializeObject

C#Jsonjson.net

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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);

Solution 2 - C#

An alternative solution for Thomas Hagström, which is my prefered, is to use the property attribute on the member variables.

For example when we invoke an API, it may or may not return the error message, so we can set the NullValueHandling property for ErrorMessage:


    public class Response
    {
        public string Status;

        public string ErrorCode;

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string ErrorMessage;
    }


    var response = JsonConvert.DeserializeObject<Response>(data);

The benefit of this is to isolate the data definition (what) and deserialization (use), the deserilazation needn’t to care about the data property, so that two persons can work together, and the deserialize statement will be clean and simple.

Solution 3 - C#

You can subscribe to the 'Error' event and ignore the serialization error(s) as required.

    static void Main(string[] args)
    {
        var a = JsonConvert.DeserializeObject<DataTable>("-- JSON STRING --", new JsonSerializerSettings
        {
            Error = HandleDeserializationError
        });
    }

    public static void HandleDeserializationError(object sender, ErrorEventArgs errorArgs)
    {
        var currentError = errorArgs.ErrorContext.Error.Message;
        errorArgs.ErrorContext.Handled = true;
    }

Solution 4 - C#

ASP.NET CORE: The accepted answer works perfectly. But in order to make the answer apply globally, in startup.cs file inside ConfigureServices method write the following:

    services.AddControllers().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    });

The answer has been tested in a .Net Core 3.1 project.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyleView Question on Stackoverflow
Solution 1 - C#Thomas HagströmView Answer on Stackoverflow
Solution 2 - C#EynzhangView Answer on Stackoverflow
Solution 3 - C#DotNetHitManView Answer on Stackoverflow
Solution 4 - C#M FuatView Answer on Stackoverflow