Avoid deserializing a JSON string token to a numeric property

Viewed 1006

The JSON looks like this:

{
    "x": "50"
}

And the class looks like this:

public class Test
{
    public float? x { get; set; }
}

And when using

var test = JsonConvert.DeserializeObject<Test>(json);

No exception is thrown, JSON.NET just converts the string value "50" into a float value 50.0.

This question is raised in the the context of input-validation. I want to get an exception, because the JSON string does not comply to the contract (the x field should be a real float).

And I don't want to use property annotations in the 'Test' class.

Is there a JsonSerializerSettings which can be be used to avoid this?

1 Answers
Related