gpt4 book ai didi

java - jackson 特定字段名称

转载 作者:行者123 更新时间:2023-12-02 10:42:40 25 4
gpt4 key购买 nike

我有这门课:

@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com