dmitry-bym / JsonKnownTypes

Simple way to serialize and deserialize polymorphic types for Json.NET
MIT License
43 stars 8 forks source link

Could not create an instance of type x Type is an interface or abstract class and cannot be instantiated. #17

Closed mathiash98 closed 3 years ago

mathiash98 commented 4 years ago

We have been running JsonKnownTypes for quite a while running smoothly. But after updating to 0.4.1 we get random errors.

Newtonsoft.Json.JsonSerializationException: Could not create an instance of type InRange.Onprem.StreamProcessing.RawMessages.RawMessageBase. Type is an interface or abstract class and cannot be instantiated. Path 'accumulateddelay', line 1, position 20. The same message works when running a unit test seperately, but when running multiple unit tests in a batch then errors occur (strange I know).

Our base class:

[JsonConverter(typeof(JsonKnownTypesConverter<RawMessageBase>))]
    [JsonDiscriminator(Name = "typename")]
    [JsonKnownType(typeof(AliveMessage), "ContikiNgAlive")]
    [JsonKnownType(typeof(DaoMessage), "ContikiNgDao")]
    [JsonKnownType(typeof(SensorMessage), "ContikiNgSensors")]
    [JsonKnownType(typeof(BeaconMessage), "ContikiNgBeacon")]
    [JsonKnownType(typeof(TestUdpMessage), "ContikiNgTestUdp")]
    [JsonKnownType(typeof(BeaconListMessage), "ContikiNgBeaconList")]
    [JsonKnownType(typeof(UpstreamData), "UPSTREAMDATA")]
    public abstract class RawMessageBase
    {

    }

I have also seen that the upgrade to 0.4.1 leads to other exceptions than in 0.4.0

[TestMethod]
        [ExpectedException(typeof(JsonReaderException))]
        public async Task HandleAsync_MalformedMessage_IsIgnored()
        {
            var bus = new Mock<IBus>();
            var handler = new MessageStreamHandler(bus.Object);
            await handler.HandleAsync("{\"hello\": \"world\"");
            bus.VerifyNoOtherCalls();
        }

^^ This test is correct on 0.4.0, but in 0.4.1 it throws JsonSerializationException instead.

We ended up downgrading to 0.4.0 which works fine. Just want to let you know that your latest fixes is not tested properly.

dmitry-bym commented 3 years ago

Major version is 0, it means that i don't guarantee that the product is completely stable, Also it means that any version can contains bracking changes because I haven't implemented it properly yet and I have to do this to make a completely correct working library