后端使用String传递给前端ID,出现精度丢失的问题,

125 阅读1分钟

现象:

数据库是bigint的数据类型,后端使用String传递给前端ID,出现精度丢失的问题。 或者使用雪花算法来增长ID

image.png

image.png

解决办法:

后端编写一个配置类,全局处理Json序列化

/**  
* @author 19324  
* 完美解决方案-雪花算法ID到前端之后精度丢失问题  
*/  
@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;  
      }  
}