關於springmvc 返回long類型數據前台丟失精度的問題


在平時開發中,遇到了一個java Long 類型字段json序列化的坑,如下:前台返回結果和數據庫中真實的值后兩位的精度丟失了,原因是因為js不支持long類型

 

解決方法兩種:

1.在字段中添加注解,默認將Long序列化成字符串,這樣前台js接收就沒有問題了(缺陷:這種辦法需要每次都手動配置,非常麻煩)

@JsonSerialize(using= ToStringSerializer.class)

 

 2.全局配置,在WebMvcConfigurer中配置json轉換器,此種辦法非常方便(缺陷:靈活度不高,對於比如微服務中互相調用,真正需要long類型傳輸,並且兩頭都能接收long類型的情況下,還需要對字符串進行轉換,顯然有些不靈活)

 1 import com.fasterxml.jackson.databind.ObjectMapper;
 2 import com.fasterxml.jackson.databind.module.SimpleModule;
 3 import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.http.converter.HttpMessageConverter;
 6 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
 7 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 8 
 9 import java.util.List;
10 
11 @Configuration
12 public class MvcConfig implements WebMvcConfigurer {
13     @Override
14     public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
15         MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
16 
17         ObjectMapper objectMapper = new ObjectMapper();
18         /**
19          * 序列換成json時,將所有的long變成string
20          * 因為js中得數字類型不能包含所有的java long值
21          */
22         SimpleModule simpleModule = new SimpleModule();
23         simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
24         simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
25         objectMapper.registerModule(simpleModule);
26 
27         jackson2HttpMessageConverter.setObjectMapper(objectMapper);
28         converters.add(0,jackson2HttpMessageConverter);
29     }
30 }

 

 總結:以上兩種方法,根據需要選擇,個人推薦只允許前端調用的接口使用第二種方式,有后台遠程調用的使用第一種方式。


免責聲明!

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



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