雪花算法 Long类型导致返回id精度缺失
实际返回参数:
“id”: 648564081745199100,
应该返回参数
“id”: “648564081745199104”
原因:
后端传给前端当Long长度大于17位时会出现精度丢失
解决方法一: 在实体类上加上
@JsonFormat(shape = JsonFormat.Shape.STRING)
@JsonFormat(shape = JsonFormat.Shape.STRING)
private Long id;
方法二: 增加webConfig类
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
/*处理返回的long类型前端无法显示问题*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
/**
* 日期全局格式化
* */
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));//GMT+8
/**
* 序列换成json时,将所有的long变成string
* 因为js中得数字类型不能包含所有的java long值
*/
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jackson2HttpMessageConverter);
}
/*处理swagger doc.html无法显示问题*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}