我尝试实现自定义Jackson
序列化程序,并且我还想在等于0.0
、writeNull()
而不是返回时处理双精度值。
这是我的序列化程序代码
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=>ZeroFee=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 {