Search code examples
jsonerror-handlingjson.netdeserialization

Ignore parsing errors during JSON.NET data parsing


I have an object with predefined data structure:

public class A
{
    public string Id {get;set;}
    public bool? Enabled {get;set;}
    public int? Age {get;set;}
}

and JSON is supposed to be

{ "Id": "123", "Enabled": true, "Age": 23 }

I want to handle JSON error in positive way, and whenever server returns unexpected values for defined data-types I want it to be ignore and default value is set (null).

Right now when JSON is partially invalid I'm getting JSON reader exception:

{ "Id": "123", "Enabled": "NotABoolValue", "Age": 23 }

And I don't get any object at all. What I want is to get an object:

new A() { Id = "123", Enabled = null, Age = 23 }

and parsing warning if possible. Is it possible to accomplish with JSON.NET?


Solution

  • To be able to handle deserialization errors, use the following code:

    var a = JsonConvert.DeserializeObject<A>("-- JSON STRING --", new JsonSerializerSettings
        {
            Error = HandleDeserializationError
        });
    

    where HandleDeserializationError is the following method:

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

    The HandleDeserializationError will be called as many times as there are errors in the json string. The properties that are causing the error will not be initialized.