Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...