由于id使用了雪花算法生成的long
今天在使id传回前端时发现,id后几位都变成了0,也就是发生了精度的损失;
查询了相关的文档以后发现,雪花算法生成的id长度有19位,而json在序列化中会将数字类型转换为16位,这样后面的精度就丢失了。默认进行了四舍五入;
所以有如下几种解决方案;
1,所有id使用String类型,弊端是字符做id查询效率比较低,
2,是使用配置类或者注解,改变序列化过程
@JsonSerialize(using = ToStringSerializer.class)
注解适用于pojo的id属性上
package com.akveo.bundlejava.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.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
{
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 全局配置序修改列化返回 Json 处理方案
SimpleModule simpleModule = new SimpleModule();
// Json Long --> String
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
ToStringSerializer别导错了包
方案3:
这个是我在网上看到的。试了一下。前端无法识别这个序列化后的字符串,不知道哪里出了问题,还在琢磨,
#解决雪花算法精度丢失
#spring.jackson.generator.write-numbers-as-strings= true