Can System.Text.Json tolerate an unrecognized type discriminator during deserialization?

2 days ago 5
ARTICLE AD BOX

I would like to be tolerant if the JSON payload contains a type my app doesn't know about. Ideally I would like to get information about the errors along with the deserialized object, but at a minimum I need to be able to get the following test to pass.

[JsonPolymorphic(IgnoreUnrecognizedTypeDiscriminators = true)] [JsonDerivedType(typeof(KnownBar), nameof(KnownBar))] interface IBar { } class KnownBar : IBar { } class Foo { public required string Hello { get; init; } public required IBar? Bar { get; init; } } [TestMethod] public void tolerate_unrecognized_discriminator() { var foo = JsonSerializer.Deserialize<Foo>( """ { "Hello": "World", "Bar": { "$type": "unrecognized" } } """); Assert.IsNotNull(foo); Assert.AreEqual("World", foo.Hello); Assert.IsNull(foo.Bar); // or assigning a NotImplementedBar would work too }

The test as written throws:

System.NotSupportedException: The JSON payload for polymorphic interface or abstract type 'Test1+IBar' must specify a type discriminator. Path: $.Bar | LineNumber: 2 | BytePositionInLine: 35.

Read Entire Article