Json保留指定小数位数和处理末尾0


//修改JsonSerializer 到需要的类型,默认为JsonSerializer,参数为Object value
public class JsonSerializerUtils extends JsonSerializer {
   @Override
    public void serialize(Double value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (Objects.nonNull(value)) {
            //保留4位小数#代表末位是0舍去
            DecimalFormat decimalFormat = new DecimalFormat("0.####");
            //四舍五入
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
            String result = decimalFormat.format(value);
            jsonGenerator.writeNumber(Double.valueOf(result));
        } else {
            jsonGenerator.writeNumber(Double.valueOf(0));
        }
    }
}
//用法实体类添加   
 @JsonSerialize(using = JsonSerializerUtils.class)
    private Double hello;

 

你可能感兴趣的:(JSON)