Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize only valid objects by ignoring errors

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 Users 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; }
}
like image 648
t3chb0t Avatar asked Jun 09 '26 11:06

t3chb0t


1 Answers

I solved this way. Not elegant.

var users = JsonConvert.DeserializeObject<IEnumerable<Object>>(json);

var usersList = users.ToList().Select(x => 
                {
                    try { return JsonConvert.DeserializeObject<User>(JsonConvert.SerializeObject(x)); } catch { return null; }
                }
            ).Where(x=> x != null).ToList<User>();
like image 191
Peterson Andrade Avatar answered Jun 11 '26 21:06

Peterson Andrade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!