写代码碰到一个bug, 现象是 后台Java返回的18位的Long类型的数据,到前台丢失了精度还有前端在数据编辑的时候出现问题

(如上图所示前端请求对象两个数字其实都是对应同一个产品的id,上面字符串没问题,下面前端同事传的数字),  查了一下,原因是

 

java的Long类型是18位, 而 js的Long类型(虽然没有明确定义的Long类型)是16位, 所以会造成丢失精度,

解决办法:

1:将后台的Long转换为字符串传回前台(其中一种较简单的方案就是在字段上面标注注解:@JsonSerialize(using = ToStringSerializer.class)),

前端提交的时候也提交字符串(如果转为数字就会失真,后台字符串会自动转化为long)

 

2:Spring Boot项目可以配置一个全局处理器,将long转行为String

 

import com.fasterxml.jackson.databind.DeserializationFeature;
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.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@EnableWebMvc
@Configuration
public class WebJsonConverterConfig implements WebMvcConfigurer {
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        //null属性不序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }
}