SpringBoot解决BigDecimal传到前端后精度丢失问题

1、局部处理

(1)在相应字段上加@JsonFormat
@JsonFormat(shape = JsonFormat.Shape.STRING)

(2)在相应字段上加@JsonSerialize
@JsonSerialize(using= ToStringSerializer.class)

 

2、全局处理

(1)ToStringSerializer
配置类
@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        // 全局配置序列化返回 JSON 处理
        SimpleModule simpleModule = new SimpleModule();
        // 将使用String来序列化BigDecimal类型
        simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}
(2)自定义序列化器
//自定义序列化类
@JacksonStdImpl
class BigDecimalToStringSerializer extends ToStringSerializer {
    public final static BigDecimalToStringSerializer instance = new BigDecimalToStringSerializer();
  
    public BigDecimalToStringSerializer() {
        super(Object.class);
    }
  
    public BigDecimalToStringSerializer(Class<?> handledType) {
        super(handledType);
    }
  
    @Override
    public boolean isEmpty(SerializerProvider prov, Object value) {
        if (value == null) {
            return true;
        }
        String str = ((BigDecimal) value).stripTrailingZeros().toPlainString();
        return str.isEmpty();
    }
  
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider)
            throws IOException {
        gen.writeString(((BigDecimal) value).stripTrailingZeros().toPlainString());
        // 如果要求所有BigDecimal保留两位小数,可以这么写:
        // gen.writeString(((BigDecimal) value).setScale(2, RoundingMode.HALF_UP)
        //         .stripTrailingZeros().toPlainString());
    }
  
    @Override
    public void serializeWithType(Object value, JsonGenerator gen,
                                  SerializerProvider provider, TypeSerializer typeSer)
            throws IOException {
        // no type info, just regular serialization
        serialize(value, gen, provider);
    }
}

//配置类
@Configuration
public class JacksonConfig {
  
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
  
        // 全局配置序列化返回 JSON 处理
        SimpleModule simpleModule = new SimpleModule();
        // 将使用String来序列化BigDecimal类型
        simpleModule.addSerializer(BigDecimal.class, BigDecimalToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}

参考:https://www.jb51.net/article/250548.htm

posted @ 2022-09-07 16:24  唏嘘-  阅读(1631)  评论(0编辑  收藏  举报