当annotation清楚地说明了具体的类型子类型信息时,为什么Jackson要将__type属性序列化为null?

zkure5ic  于 2023-03-23  发布在  其他
关注(0)|答案(1)|浏览(113)

我有一个使用allOf的open API v2模式,并通过openapi-generator-maven-plugin生成如下所示的模型类。

@JsonPropertyOrder({
  TradeRequest.JSON_PROPERTY_TYPE,
  TradeRequest.JSON_PROPERTY_BUSINESS_DATE
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2023-02-23T11:48:40.067Z[Europe/London]")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "__type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = ConcreteRequest.class, name = "ConcreteRequest"),
})

public class BaseRequest {
  public static final String JSON_PROPERTY_TYPE = "__type";
  protected String type;

  public static final String JSON_PROPERTY_BUSINESS_DATE = "businessDate";
  private LocalDate businessDate;

  public BaseRequest type(String type) {    
    this.type = type;
    return this;
  }

  @ApiModelProperty(required = true, value = "")
  @JsonProperty(JSON_PROPERTY_TYPE)
  @JsonInclude(value = JsonInclude.Include.ALWAYS)
  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public BaseRequest businessDate(LocalDate businessDate) {
    this.businessDate = businessDate;
    return this;
  }

  @javax.annotation.Nullable
  @ApiModelProperty(value = "")
  @JsonProperty(JSON_PROPERTY_BUSINESS_DATE)
  @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)

  public LocalDate getBusinessDate() {
    return businessDate;
  }

  public void setBusinessDate(LocalDate businessDate) {
    this.businessDate = businessDate;
  }
}

@JsonPropertyOrder({
  EnrichTradeRequest.JSON_PROPERTY_SOAP_TRADE_INPUT
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2023-02-23T11:48:40.067Z[Europe/London]")
public class ConcreteRequest extends BaseRequest {
  public static final String JSON_PROPERTY_SOAP_TRADE_INPUT = "soapTradeInput";
  private SoapTradeInput soapTradeInput;

  public ConcreteRequest soapTradeInput(SoapTradeInput soapTradeInput) {
    this.soapTradeInput = soapTradeInput;
    return this;
  }

  @javax.annotation.Nullable
  @ApiModelProperty(value = "")
  @JsonProperty(JSON_PROPERTY_SOAP_TRADE_INPUT)
  @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
  public SoapTradeInput getSoapTradeInput() {
    return soapTradeInput;
  }

  public void setSoapTradeInput(SoapTradeInput soapTradeInput) {
    this.soapTradeInput = soapTradeInput;
  }
}

我去掉了equals / toString / hashCode方法。
如果我创建一个ConcreteRequest的示例,并使用如下所示的对象Map器将其序列化为json,则__type属性为空
x一个一个一个一个x一个一个二个x
假定对象图显式地使用具体类型和引用,我希望__type值自动地为我序列化,并且我不应该显式地设置对象的属性。
我怀疑这是一个配置问题,但我不确定如何确保在序列化到json时为__type使用正确的具体类型值。

ffscu2ro

ffscu2ro1#

我没有看到BaseRequest.typeConcreteRequest的构造函数中被设置。
也许你需要这样做:

public ConcreteRequest() {
        setType("ConcreteRequest");
    }

相关问题