使用杰克逊序列化,如何序列化双精度值 null 并且在 0.0 时不返回



我尝试实现自定义Jackson序列化程序,并且我还想在等于0.0writeNull()而不是返回时处理双精度值。
这是我的序列化程序代码

public class DoubleGTZeroSerializer extends JsonSerializer<Double> {
private DecimalFormat df = new DecimalFormat("##.##");
@Override
public Class<Double> handledType() {
return Double.class;
}
@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
if (value != null && value.doubleValue() > 0) {
gen.writeString(df.format(value));
} else {
gen.writeNull();
}
}
}

下面是波乔

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Bill implements Serializable {
private static final long serialVersionUID = -5034123031564773631L;
@JsonSerialize(using = DoubleToStringSerializer.class)
private Double orderFee;
@JsonSerialize(using = DoubleToStringAfterSymbolSerializer.class)
private Double transFee;
@JsonSerialize(using = DoubleToStringBeforeSymbolSerializer.class)
private Double otherFee;
@JsonSerialize(using = DoubleGTZeroSerializer.class)
private Double gtZeroFee;
...
}

我的要求是 http://localhost:5509/test?orderFee=10.1&transFee=100.00&otherFee=&gtZeroFee=0 API 结果

{
"status": {
"desc": "操作成功",
"code": 0
},
"data": [
{
"orderFee": "10.1",
"transFee": "100元",
"gtZeroFee": null
}
],
"success": true
}

我不想把gtZeroFee@JsonInclude(JsonInclude.Include.NON_NULL)null,但注释不起作用,请帮助我,谢谢大家。

相反,您可以使用JsonInclude.Include.NON_EMPTY并实现isEmpty方法JsonInclude.Include.NON_NULL

class DoubleGTZeroSerializer extends JsonSerializer<Double> {
private DecimalFormat df = new DecimalFormat("##.##");
@Override
public Class<Double> handledType() {
return Double.class;
}
@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(df.format(value));
}
@Override
public boolean isEmpty(SerializerProvider provider, Double value) {
return value <= 0;
}
}

并将Bill注释更改为:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
class Bill implements Serializable {

最新更新