SpringBoot给前端返回long型字段精度丢失问题

最近在做一个项目的时候遇到了以long型保存id的问题,以Json格式返回到前台就精度丢失了。 造成这个问题的原因是:在JS中没用Long型的数据类型,所以回精度丢失。 解决办法:全局配置,返回long型数据的时候转成String类型

import com.fasterxml.jackson.annotation.JsonInclude;
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.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

// 将long型字段转成String并输出
@JsonComponent
public class JsonSerializerManage {
          
   

    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
          
   
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //忽略value为null 时 key的输出
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 序列换成json时,将所有的long变成string
        // 因为js中得数字类型不能包含所有的java long值
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(module);
        return objectMapper;
    }
}
经验分享 程序员 微信小程序 职场和发展