Live2D

Long数据类型序列化Json后传递给前端,产生的精度丢失的问题解决

问题产生的原因

Long类型的数据,如果我们在后端将结果序列化为json,直接传给前端的话,在Long长度大于17位时会出现精度丢失的问题。 java中的long能表示的范围比js中number大,也就意味着部分数值在js中存不下(变成不准确的值),比如此案例中Id最后两位直接变成了0

 

解决方案

添加配置类

复制代码
package baselib.cunyt.cn.common.mvc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.math.BigInteger;

/**
 * 解决java Long转json精度丢失的问题
 *
 * @author wupeiguo
 */

@Configuration
public class ApiMvcConfiguration {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
    {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        // 全局配置序列化返回 JSON 处理
        SimpleModule simpleModule = new SimpleModule();
        //JSON Long ==> String
        //超长整
        simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
        //长整
        simpleModule.addSerializer(Long.class,ToStringSerializer.instance);
        //长整
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}
复制代码

转载自:

https://blog.csdn.net/YangYF1997/article/details/119828164

https://www.csdn.net/tags/Mtjagg0sMDI1NzMtYmxvZwO0O0OO0O0O.html

posted @   都是朕的江山  阅读(414)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
返回顶端
点击右上角即可分享
微信分享提示