SpringBoot BigDecimal精度丢失
- jackjson自动丢弃了小数位最末尾的0
private BigDecimal price; price=12.10; 返回自动转为了12.1
- 解决方案
- 1: 返回字段都用字符串
- 2:BigDecimal序列化自定义处理
package com.lenovo.lps.cost.integrator.config; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import lombok.SneakyThrows; import java.math.BigDecimal; public class BigDecimalSerializer extends JsonSerializer<BigDecimal> { @SneakyThrows @Override public void serialize(BigDecimal bigDecimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) { if (null != bigDecimal) { String plainString = bigDecimal.toPlainString(); jsonGenerator.writeString(plainString); } } }
- 在返回的对象属性上引用序列化类
@JsonSerialize(using = BigDecimalSerializer.class) private BigDecimal variablePrice;