Is there a built-in way (or a trick) for parsing only valid objects and ignoring invalid ones?
Not a duplicate
The question Ignoring an invalid field when deserializing json in Json.Net does not answer my question because it's about a custom serializer for a very specific field of date-time type. I'm seeking a generic solution working for any property and any object.
In other words if anything is invalid, just ignore it and contintue to the next entry. As far as json is concerned, the file is correct but the content might not match the expected types in some places. It can by anything.
Background: The file contains an array of many workflows and a single damaged entry should not break the entire configuration and virtually disable them all.
Here's an example demonstrating what I mean. Let's say I have an array of User
s but one entry instead of using a string
for the Name
uses an array (it might by any combination of invalid values, like an object where an array is expected.
I'd like to deserialize this array and ignore entries that couldn't be deserialized. This means that the expected result should be two users, John & Tom.
I tried to use the Error
handler but it does not work this way. It doesn't allow me to skip the errors.
void Main()
{
var json = @"
[
{
'Name': 'John',
},
{
'Name': [ 'John' ]
},
{
'Name': 'Tom',
},
]
";
var users = JsonConvert.DeserializeObject<IEnumerable<User>>(json, new JsonSerializerSettings
{
Error = (sender, e) =>
{
e.Dump();
e.ErrorContext.Handled = true;
e.CurrentObject.Dump();
}
}).Dump();
}
class User
{
public string Name { get; set; }
}