![](/img/trans.png)
[英]How to deserialize a class with overloaded constructors using JsonCreator
[英]Using @JsonCreator to create two instances of same class in one 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;
}
我想用@JsonCreator
創建這兩個ObjectPricingSetting
實例。
問:我應該如何在ObjectPricingSetting
構造函數中注釋@JsonProperty
參數以識別應該使用什么 JSON 值來創建這兩個實例?
您可以在父 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;
}
然后你可以在你的嵌套 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.