java - 使用 @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
with实例@JsonCreator
。
问:我应该如何@JsonProperty
在构造函数中注释参数ObjectPricingSetting
以识别应该使用什么 JSON 值来创建这两个实例?
解决方案
您可以在父类中使用带有前缀的 @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) {
...
推荐阅读
- excel - 无法打印由函数填充的子过程中的所有结果
- typescript - 打字稿:排除
不排除我的类型 - sql - 实体框架 6 对 IDictionary 的自定义查询
- android - 如何禁用拉刷新,当刷回收器视图项目时?
- ios - HTTPURLResponse.localizedString(forStatusCode:) 不是开发语言
- javascript - 在 GCP App Engine 中使用 NodeJs 和 Babel 的问题
- node.js - 如何为嵌套数据设计猫鼬模式设计
- excel - 将数据从一个工作簿复制到另一个工作簿的最后一行
- python - 何时使用“For Loop vs List Comprehension”创建新列表?
- ios - 有什么方法可以在没有开发人员帐户的情况下共享我的 iPhone 应用程序进行测试?