解决前后端交互Long类型精度丢失问题
现象
ID较长,传到前端后,精度丢失
如:
后端传递:1396677407141314562
前端接收:1396677407141314500
一、解决方法
将Long类型转成String,再传给前端
1.单个注解
方法一:单个注解:
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
2.方法二:统一配置
方法二:统一配置:
package com.zhongchuangwang.digital.config;
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.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* 统一注解,解决前后端交互Long类型精度丢失的问题
*/
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}