0
点赞
收藏
分享

微信扫一扫

浏览器Long精度丢失问题简记

背景说明

近期项目编码联调过程中发现Long类型的主键通过Ajax请求返回Chrome浏览器后出现了不一致的情况,不一致情况经过对比发现前面是一样的后面几位是0,尝试使用PostMan进行接口请求发现返回的主键是正确的。

解决方案

JavaScript中的Number类型并不能完全表示Long类型的数字,当Long长度大于17位时会出现精度丢失的问题,浏览器会自动把超出部分用0表示。

方案一

目前成熟的解决方案使后端返回的主键为字符串类型,使用字符串类型进行数据交互。

方案二

因为工程中使用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 转换long型,精度丢失的问题-->
<bean id="fastJsonConfigExt" class="com.jhf.config.FastJsonConfigExt"/>

<!-- 解决@ResponseBody注解直接返回对象并转换成JSON时出现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

举报

相关推荐

0 条评论