1

Closed

CanConvert not called with JsonConverterAttribute

description

        private class DataClass
        {
            [JsonConverter(typeof(CharBoolConverter))]
            public bool Data { get; set; }
        }

        [Fact]
        public void ReadJson()
        {
            string nullJson = @"{'data': null}";
            string trueJson = @"{'data': 'Y'}";
            string falseJson = @"{'data': 'N'}";
            string emptyJson = @"{'data': ''}";
            string errorJson = @"{'data': 'herp derp'}";

            Assert.True(JsonConvert.DeserializeObject<DataClass>(trueJson).Data);
            Assert.False(JsonConvert.DeserializeObject<DataClass>(falseJson).Data);
            Assert.False(JsonConvert.DeserializeObject<DataClass>(emptyJson).Data);
            Assert.False(JsonConvert.DeserializeObject<DataClass>(nullJson).Data);
            Assert.Throws<Exception>(() => 
                JsonConvert.DeserializeObject<DataClass>(errorJson));
        }
When checking test code coverage in visual studio, if I use the JsonConverter attribute in my DataClass, I get zero coverage on the CanConvert method. If I pass it as a converter in DeserializeObject, CanCovert does get coverage. Is it intentional that CanCovert does not get called when using JsonConverterAttribute?

Is CanConvert only used to find a valid converter for a property when the SerializerSettings contains multiple converters?
Closed May 3, 2013 at 9:35 AM by JamesNK
It is intentional. JsonConverterAttribute is loaded by the CLR when the type is loaded, and an exception thrown in it if CanConvert was false could be thrown from anywhere, on any thread.

comments