背景說明
近期項目編碼聯(lián)調(diào)過程中發(fā)現(xiàn)Long類型的主鍵通過Ajax請求返回Chrome瀏覽器后出現(xiàn)了不一致的情況,不一致情況經(jīng)過對比發(fā)現(xiàn)前面是一樣的后面幾位是0,嘗試使用PostMan進行接口請求發(fā)現(xiàn)返回的主鍵是正確的。
解決方案
JavaScript中的Number類型并不能完全表示Long類型的數(shù)字,當(dāng)Long長度大于17位時會出現(xiàn)精度丟失的問題,瀏覽器會自動把超出部分用0表示。
Chrome從第17位就開始作妖(有時候正常,有時候+1),18位以及后面均補0
方案一
目前成熟的解決方案使后端返回的主鍵為字符串類型,使用字符串類型進行數(shù)據(jù)交互。
方案二
因為工程中使用FastJson比較多,這里提供方案如下
public class FastJsonConfigExt extends FastJsonConfig {
public FastJsonConfigExt(){
super();
SerializeConfig serializeConfig = SerializeConfig.globalInstance;
serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
serializeConfig.put(Long.class,ToStringSerializer.instance);
serializeConfig.put(Long.TYPE,ToStringSerializer.instance);
this.setSerializeConfig(serializeConfig);
}
}
Bean配置
<!--解決fastJson 轉(zhuǎn)換long型,精度丟失的問題-->
<bean id="fastJsonConfigExt" class="com.jhf.config.FastJsonConfigExt"/>
<!-- 解決@ResponseBody注解直接返回對象并轉(zhuǎn)換成JSON時出現(xiàn)406問題,同時解決了返回String類型亂碼的問題 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="fastJsonConfig" ref="fastJsonConfigExt" />
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
<property name="features">
<list>
<!-- null String也要輸出 -->
<value>WriteMapNullValue</value>
<!-- 輸出key時是否使用雙引號 -->
<value>QuoteFieldNames</value>
<!-- 字符類型字段如果為null,輸出為"",而非null -->
<value>WriteNullStringAsEmpty</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Jackson處理方式參見:https://blog.csdn.net/haha_66666/article/details/86494853