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 @ 2022-11-08 00:55  都是朕的江山  阅读(481)  评论(0)    收藏  举报
返回顶端