Код: Выделить всё
[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(
"""
{
"Hello": "World",
"Bar": { "$type": "unrecognized" }
}
""");
Assert.IsNotNull(foo);
Assert.AreEqual("World", foo.Hello);
Assert.IsNull(foo.Bar); // or assigning a NotImplementedBar would work too
}
System.NotSupportedException: полезные данные JSON для полиморфного интерфейса или абстрактного типа «Test1+IBar» должны указывать дискриминатор типа. Путь: $.Bar | Номер строки: 2 | BytePositionInLine: 35.
Подробнее здесь: https://stackoverflow.com/questions/798 ... g-deserial
Мобильная версия