.NET 8中System.Text.Json多态反序列化空值及异常问题咨询
Step 1: Fix the Class Interface Implementation
Your SpecificMessage class doesn't implement the ISpecificMessage interface, which breaks the polymorphic inheritance chain. Update it to explicitly implement the interface:
public interface ISomething { } // Ensure this interface is defined public interface IBaseMessage { } [JsonDerivedType(typeof(SpecificMessage))] public interface ISpecificMessage : IBaseMessage, ISomething { } // Implement ISpecificMessage in the concrete class public class SpecificMessage : ISpecificMessage { public IBaseMessage Message { get; set; } }
Step 2: Configure Polymorphism on the Base Interface
The error "Deserialization of interface types is not supported" occurs because you tried mapping a derived interface (ISpecificMessage) directly in IBaseMessage's attributes. Instead, map the concrete type (SpecificMessage) to the base interface using JsonPolymorphic to enable polymorphic handling:
[JsonPolymorphic] [JsonDerivedType(typeof(SpecificMessage))] public interface IBaseMessage { }
Handling Custom Type Discriminators (If Needed)
If your incoming JSON uses the interface name (e.g., "$type": "ISpecificMessage") as the discriminator instead of the concrete class name, specify the typeDiscriminator parameter to map it correctly:
[JsonPolymorphic] [JsonDerivedType(typeof(SpecificMessage), typeDiscriminator: "ISpecificMessage")] public interface IBaseMessage { }
Why This Works
JsonPolymorphiconIBaseMessagetells System.Text.Json to handle polymorphic deserialization for this interface.JsonDerivedType(typeof(SpecificMessage))maps the concrete class to the base interface, allowingIBaseMessageproperties to deserialize intoSpecificMessageinstances.- Ensuring
SpecificMessageimplementsISpecificMessagevalidates the inheritance hierarchy, making the polymorphic mapping valid.
This setup will correctly deserialize your IBaseMessage field into a SpecificMessage instance without requiring custom converters.
内容的提问来源于stack exchange,提问作者leopcode

