[英]Using @JsonCreator to create two instances of same class in one JSON DTO
I would like to deserialize JSON of this structure:我想反序列化这个结构的 JSON :
{
"employee_pricing_type":"COMPUTE_BY_OWN_RATE",
"employee_rate":10,
"customer_pricing_type":"COMPUTE_BY_OWN_RATE",
"customer_rate":200
}
I have such POJO to create price setting from a HTTP request:我有这样的 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;
}
}
this is DTO:这是 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;
}
I would like to create these two instances of ObjectPricingSetting
with @JsonCreator
.我想用
@JsonCreator
创建这两个ObjectPricingSetting
实例。
Q: How should I anotate @JsonProperty
parameter in ObjectPricingSetting
constructor to recognize what JSON value should use to create these two instances?问:我应该如何在
ObjectPricingSetting
构造函数中注释@JsonProperty
参数以识别应该使用什么 JSON 值来创建这两个实例?
You can use @JsonUnwrapped with a prefix in your parent class:您可以在父 class 中使用带有前缀的 @JsonUnwrapped:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ObjectPricingCommand extends BaseDto<ObjectId> {
@JsonUnwrapped(prefix = "employee_")
private ObjectPricingSetting employeePricingSetting;
@JsonUnwrapped(prefix = "customer_")
private ObjectPricingSetting customerPricingSetting;
}
Then you can use the normal @JsonCreator/@JsonProperty in your nested DTO, without the prefix:然后你可以在你的嵌套 DTO 中使用普通的 @JsonCreator/@JsonProperty,没有前缀:
public class ObjectPricingSetting {
@JsonCreator
public ObjectPricingSetting(
@JsonProperty("pricing_type") final ObjectPricingType pricingType,
@JsonProperty("rate") final BigDecimal ownRate) {
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.