1. 程式人生 > 實用技巧 >關於springmvc 返回long型別資料前臺丟失精度的問題

關於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 }

總結:以上兩種方法,根據需要選擇,個人推薦只允許前端呼叫的介面使用第二種方式,有後臺遠端呼叫的使用第一種方式。