版权声明
- 本文原创作者:谷哥的小弟
- 作者博客地址:http://blog.csdn.net/lfdfhl
问题描述
项目中采用雪花ID。该ID在后端中为Long类型,在前端中为number类型。但是,Long和number的精度不一样;故,会导致数据精度丢失。示例如下:
后端数据:34564858876302984
前端数据:34564858876302980
解决方案
在此,介绍两种常用的解决方案。
方案一
在后端将Long类型转成String再传给前端。
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
方案二
在后端使用注解解决前后端交互Long类型精度丢失的问题。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
@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;
}
}