1
static void Main(string[] args)
{
    const string someSerializedValue = "{\"SomeValue\":true}";
    var stringBool = JsonConvert.DeserializeObject<StringBool>(someSerializedValue);
    var actualBool = JsonConvert.DeserializeObject<ActualBool>(someSerializedValue);
}

private class StringBool
{
    // I want this to fail
    public string SomeValue { get; set; }
}

private class ActualBool
{
    public bool SomeValue { get; set; }
}

Note that SomeValue is a boolean true in JSON. So I'd like the deserialization step to fail for stringBool. But it doesn't. Is there an attribute that will be more strict about what valid deserialization is in cases like this?

rianjs
  • 7,767
  • 5
  • 24
  • 40
  • Out of curiousity if you control the deserialization property names and types how would this ever be an issue? – The Muffin Man Sep 27 '17 at 20:10
  • Yes, that's the point: the type isn't being respected. JSON.NET is deserializing `{"SomeValue":true}` into `string SomeValue = "true"`. If the client were sending `{"SomeValue":"true"}`, that would be make sense. But they're not. So yes, I control the type, but the serializer is doing something unexpected here WRT types. (It does the same thing with numbers.) – rianjs Sep 27 '17 at 20:19
  • 1
    You could create `StrictStringConverter` along the lines of `StrictIntConverter` from [JSON Deserialization - String Is Automatically Converted To Int](https://stackoverflow.com/a/41784433) and [How to let deserialization throw exception on non-integer where expecting an int?](https://stackoverflow.com/a/45777434). – dbc Sep 27 '17 at 22:47

0 Answers0