使用@JsonCreator 在一个 JSON DTO 中创建同一个类的两个实例

问题描述

我想反序列化这个结构的 JSON:

{
"employee_pricing_type":"COmpuTE_BY_OWN_RATE","employee_rate":10,"customer_pricing_type":"COmpuTE_BY_OWN_RATE","customer_rate":200    
}

我有这样的 POJO 从 HTTP 请求创建价格设置:

public class ObjectPricingSetting {

  @JsonProperty("pricing_type") // describes output 
  private final ObjectPricingType pricingType;

  @JsonProperty("own_rate") // describes output 
  private final BigDecimal ownRate;

  public ObjectPricingSetting(final ObjectPricingType pricingType,final BigDecimal ownRate) {

    AssertUtils.notNull(pricingType,"pricingType");
    this.pricingType = pricingType;

    if (ownRate != null) {
      AssertUtils.isGtZero(ownRate,"ownRate");
      this.ownRate = ownRate;
    } else {
      this.ownRate = null;
    }

  }

  public ObjectPricingType getPricingType() {
    return pricingType;
  }

  public BigDecimal getownRate() {
    return ownRate;
  }

}

这是 DTO:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ObjectPricingCommand extends BaseDto<ObjectId> {

  @JsonProperty(value = "employee_pricing_setting")
  private ObjectPricingSetting employeePricingSetting;

  @JsonProperty(value = "customer_pricing_setting")
  private ObjectPricingSetting customerPricingSetting;

}

我想用 ObjectPricingSetting 创建这两个 @JsonCreator 实例。

问:我应该如何在 @JsonProperty 构造函数中注释 ObjectPricingSetting 参数以识别应该使用什么 JSON 值来创建这两个实例?

解决方法

您可以在父类中使用带有前缀的@JsonUnwrapped:

external: [
    'react','prop-types',],

然后您可以在嵌套的 DTO 中使用普通的 @JsonCreator/@JsonProperty,而无需前缀:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ObjectPricingCommand extends BaseDto<ObjectId> {

  @JsonUnwrapped(prefix = "employee_")
  private ObjectPricingSetting employeePricingSetting;

  @JsonUnwrapped(prefix = "customer_")
  private ObjectPricingSetting customerPricingSetting;

}