Using Newtonsoft.Json, I need to deserialize a json which contains the number '2.696539702293474e308' which is their way of expressing a NaN

the following code almost works


public class MyClass
{
    public double[] VectorOfDoubles;
}

private static void Do()
{
    var errors = new List<string>();

    var content = "{ " +
        "\"VectorOfDoubles\" : [0.2, 0.3] " +
        ", \"WithNans\" : [0.4, 2.696539702293474e308] " +
        "}";

    var output = JsonConvert.DeserializeObject<MyClass>(content, new JsonSerializerSettings
    {
        Error = (currentObject, errorArgs) =>
        {
            errors.Add(errorArgs.ErrorContext.Error.Message);
            errorArgs.ErrorContext.Handled = true;
        },
    });
}

With the above example I get what I need: .DeserializeObject returns a MyClass with 'VectorOfDoubles' populated. I actually don't even care about the 'WithNans' vector. There is correctly one item in 'errors':

"Input string '2.696539702293474e308' is not a valid number. Path 'WithNans[1]', line 1, position 75."

The problem arise if the WithNans contains more then one offending item, like

"WithNans" [0.4, 2.696539702293474e308, 2.696539702293474e308]

In this case errors contains two items but .DeserializeObject returns null

Why? Is there a way to fully ignore all items on a certain field?

0 Answers