作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这门课:
@Data
public class DiscountDto {
@JsonProperty(required = true)
private DiscountType type;
@JsonProperty(required = true)
private double discountValue;
}
DiscountType 是枚举:
public enum DiscountType {
PERCENT, AMOUNT
}
我想根据枚举值将 discountValue
序列化为特定值。如果枚举具有值PERCENT
,则discountValue必须序列化为percent_off
。如果枚举的值为 AMOUNT
,则 discountValue
必须序列化为 amount_off
。我怎么可能这么做?
预期结果:
如果类型== AMOUNT,我想要discountValue name = amount_off
"discountDto": {
"amount_off": "11.0",
"type": "AMOUNT"
}
如果类型== PERCENT,我想要discountValue name = percent_off
"discountDto": {
"percent_off": "11.0",
"type": "PERCENT"
}
最佳答案
可能的解决方案:
1.创建一个同时包含DiscountType和discountValue的构造函数,并直接设置percentOff或amountOff字段的值:
@JsonInclude(Include.NON_NULL)
public class DiscountDto {
private DiscountType type;
@JsonProperty("percent_off")
private Double percentOff;
@JsonProperty("amount_off")
private Double amountOff;
public DiscountDto(DiscountType type, double discountValue){
this.type = type;
if(type.equals(DiscountType.PERCENT)){
this.percentOff = discountValue;
}else {
this.discountOff = discountValue;
}
}
//getters and setters
}
2.使用自定义 JSON 序列化器:
public class DiscountDtoSerializer extends StdSerializer<DiscountDto> {
public DiscountDtoSerializer() {
this(null);
}
public DiscountDtoSerializer(Class<DiscountDto> t) {
super(t);
}
@Override
public void serialize(DiscountDto value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("type", value.getDiscountType());
if(value.getDiscountType().equals(DiscountType.PERCENT)){
jgen.writeStringField("percent_off", value.getDiscountValue());
}else{
jgen.writeStringField("amount_off", value.getDiscountValue());
}
jgen.writeEndObject();
}
}
并且您的 ObjectMapper 应该有这个新的序列化器:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(DiscountDto.class, new DiscountDtoSerializer());
mapper.registerModule(module);
关于java - jackson 特定字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52817455/
概述 CentOS Stream 成立于 2019 年,是“RHEL 下一步的滚动预览”。Red Hat 首席技术官 Chris Wright 和 CentOS 社区经理 Rich Bowen 各
我有一个使用 Mesosphere DC/OS 编排选项进行配置的 Azure 容器服务 (ACS) 集群。我可以在 Marathon UI 中创建一个应用程序。 但是,当我通过 Marathon U
我是一名优秀的程序员,十分优秀!