You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8中System.Text.Json多态反序列化空值及异常问题咨询

Solution for System.Text.Json Polymorphic Deserialization in .NET 8

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

  • JsonPolymorphic on IBaseMessage tells System.Text.Json to handle polymorphic deserialization for this interface.
  • JsonDerivedType(typeof(SpecificMessage)) maps the concrete class to the base interface, allowing IBaseMessage properties to deserialize into SpecificMessage instances.
  • Ensuring SpecificMessage implements ISpecificMessage validates 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:54:55