最近在改造內部管理系統的時候, 發現了一個巨坑,就是前端 JS 在獲取後端 Long 型參數時,出現精度丟失!前端
起初,用 postman 模擬接口請求,都很正常,可是用瀏覽器請求的時候,就出現問題了!java
問題復現spring
@RequestMapping("/queryUser") public List<User> queryUser(){ List<User> resultList = new ArrayList<>(); User user = new User(); //賦予一個long型用戶ID user.setId(123456789012345678L); resultList.add(user); return resultList; }
打開瀏覽器,請求接口,結果以下!數據庫
用 postman 模擬接口請求,結果以下!json
剛開始的時候,還真沒發現這個坑,結果當進行測試的時候,才發現前端傳給後端的ID,與數據庫中存的ID不一致,才發現 JavaScript 還有這個天坑!
後端
因爲 JavaScript 中 Number 類型的自身緣由,並不能徹底表示 Long 型的數字,在 Long 長度大於17位時會出現精度丟失的問題。數組
當咱們把上面的用戶 ID 改爲 19 位的時候,咱們再來看看瀏覽器請求返回的結果。瀏覽器
//設置用戶ID,位數爲19位user.setId(1234567890123456789l);
瀏覽器請求結果!mvc
當返回的結果超過17位的時候,後面的所有變成0!
app
遇到這種狀況,應該怎麼辦呢?
第一種辦法:在後臺把 long 型改成String類型,可是代價有點大,只要涉及到的地方都須要改
第二種辦法:使用工具進行轉化把 long 型改成String類型,這種方法能夠實現全局轉化(推薦)
第三種辦法:前端進行處理(目前沒有很好的辦法,不推薦)
由於項目涉及到的代碼很是多,因此不可能把 long 型改成 String 類型,並且使用 Long 類型的方法很是多,改起來風險很是大,因此不推薦使用!
最理想的方法,就是使用aop代理攔截全部的方法,對返回參數進行統一處理,使用工具進行轉化,過程以下!
咱們可使用Jackson工具包來實現對象序列化。
首先在 maven 中添加必須的依賴
<!--jackson依賴--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency>
編寫一個轉化工具類JsonUtil
public class JsonUtil {
private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
private static ObjectMapper objectMapper = new ObjectMapper(); private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
static { // 對象的全部字段所有列入 objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); // 取消默認轉換timestamps形式 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // 忽略空bean轉json的錯誤 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //設置爲東八區 objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 統一日期格式 objectMapper.setDateFormat(new SimpleDateFormat(DATE_FORMAT)); // 反序列化時,忽略在json字符串中存在, 但在java對象中不存在對應屬性的狀況, 防止錯誤 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 序列換成json時,將全部的long變成string objectMapper.registerModule(new SimpleModule().addSerializer(Long.class, ToStringSerializer.instance).addSerializer(Long.TYPE, ToStringSerializer.instance)); }
/** * 對象序列化成json字符串 * @param obj * @param <T> * @return */ public static <T> String objToStr(T obj) { if (null == obj) { return null; }
try { return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj); } catch (Exception e) { log.warn("objToStr error: ", e); return null; } }
/** * json字符串反序列化成對象 * @param str * @param clazz * @param <T> * @return */ public static <T> T strToObj(String str, Class<T> clazz) { if (StringUtils.isBlank(str) || null == clazz) { return null; }
try { return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz); } catch (Exception e) { log.warn("strToObj error: ", e); return null; } }
/** * json字符串反序列化成對象(數組) * @param str * @param typeReference * @param <T> * @return */ public static <T> T strToObj(String str, TypeReference<T> typeReference) { if (StringUtils.isBlank(str) || null == typeReference) { return null; }
try { return (T) (typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str, typeReference)); } catch (Exception e) { log.warn("strToObj error", e); return null; } }}
緊接着,編寫一個實體類Person,用於測試
@Datapublic class Person implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
//Long型參數 private Long uid; private String name; private String address; private String mobile;
private Date createTime;}
最後,咱們編寫一個測試類測試一下效果
public static void main(String[] args) { Person person = new Person(); person.setId(1); person.setUid(1111L); person.setName("hello"); person.setAddress(""); System.out.println(JsonUtil.objToStr(person)); }
輸出結果以下:
其中最關鍵一行代碼,是註冊了這個轉換類,從而實現將全部的 long 變成 string。
// 序列換成json時,將全部的long變成string SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); objectMapper.registerModule(simpleModule);
若是想對某個日期進行格式化,能夠全局設置。
//全局統一日期格式 objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
也能夠,單獨對某個屬性進行設置,例如對createTime屬性格式化爲yyyy-MM-dd,只須要加上以下註解便可。
@JsonFormat(pattern="yyyy-MM-dd", timezone="GMT+8") private Date createTime;
工具轉化類寫好以後,就很是簡單了,只須要對 aop 攔截的方法返回的參數,進行序列化就能夠自動實現將全部的 long 變成 string。
若是是 SpringMVC 項目,操做也很簡單。
自定義一個實現類,繼承自ObjectMapper
package com.example.util;
/** * 繼承ObjectMapper */public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() { super(); SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); registerModule(simpleModule); }}
在 SpringMVC 的配置文件中加上以下配置
<mvc:annotation-driven > <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructorarg index="0" value="utf8" /> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> <value>text/plain;charset=UTF8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.example.util.CustomObjectMapper"> <property name="dateFormat"> <-對日期進行統一轉化-> <bean class="java.text.SimpleDateFormat"> <constructor-arg type="java.lang.String" value="yyyyMMdd HH:mm:ss" /> </bean> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
若是是 SpringBoot 項目,操做也相似。
編寫一個WebConfig配置類,並實現自WebMvcConfigurer,重寫configureMessageConverters方法
/** * WebMvc配置 */@Configuration@Slf4j@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer {
/** *添加消息轉化類 * @param list */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> list) { MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = jsonConverter.getObjectMapper(); //序列換成json時,將全部的long變成string SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); objectMapper.registerModule(simpleModule); list.add(jsonConverter); }}
在實際的項目開發中,不少服務都是純微服務開發,沒有用到SpringMVC,在這種狀況下,使用JsonUtil工具類實現對象序列化,多是一個很是好的選擇。