springboot中關於Long類型返回前端精度丟失問題處理


使用了HuTool這個雪花算法后,會出現丟失精度的問題

hutool算法使用地址

對於一些大的業務表,自增主鍵這里 接口層得注意下是否會產生大數值 設計接口的時候采用String類型。
在項目中,我們可能采取bigint作為數據庫主鍵,Java類中我們一般采用Long類型來映射。對於大數值比如1218106361019314176,數據在服務端好好的,到了前端會發現變成1218106361019314200,造成精度丟失,這樣顯然是有問題的。

解決辦法:
我們只需要配置一下json配置即可,把所有Long型的字段轉成String型即可。(本文是基於springboot2.1,其他版本基本一樣)

@Configuration
public class LongToStringJsonConfig extends WebMvcConfigurationSupport {
   
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM