前端页面响应Long型数据造成精度丢失

178 阅读1分钟

原因

由于js处理Long型数据时会导致精度丢失

解决思路

在服务器给前端页面响应json数据时进行数据处理,将Long型的数据统一转换成String类型。

解决方法

第一步: 提供一个对象转换器。基于jackson进行json到java数据的互相转换

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
/**
 * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
 * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
 * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
 */
public class JacksonObjectMapper extends ObjectMapper {
    public JacksonObjectMapper() {
        super();
        //收到未知属性时不报异常
        this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);

        //反序列化时,属性不存在的兼容处理
        this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);


        SimpleModule simpleModule = new SimpleModule()
                .addSerializer(Long.class, ToStringSerializer.instance)//为Long的数据做一个转换处理

        //注册功能模块 例如,可以添加自定义序列化器和反序列化器
        this.registerModule(simpleModule);
    }
}

第二步:在WebMvcConfig配置类中扩展Spring MVC 的消息转换器,在此消息转换器中调用第一步提供的对象转换器进行java数据与json的转化(在转换时进行的Long->String)

@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    //创建消息转换器对象
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
    //设置对象转换器,底层使用Jackson将java对象转换成Json对象
    messageConverter.setObjectMapper(new JacksonObjectMapper());
    //将上面的消息转换器对象追加到MVC框架的转换器集合中(需要指定优先级,此处直接为最高级0,因为需要优先使用自己的转换器,否则会被内置转换器 覆盖)
    converters.add(0,messageConverter);
}