long类型的id属性传到前端会精度丢失的解决方案

解决方法:ProjectDTO.java文件采用一方案

直接在实体类的id属性上面加上注解 @JsonSerialize(using = ToStringSerializer.class)
这样一来,在后端依然是 long 类型,当实体类序列化成JSON的时候,在JSON中这个属性就会变成string类型。

    @Id
    @GeneratedValue
    @JsonSerialize(using = ToStringSerializer.class)
    @ApiModelProperty(value = "主键ID/非必填")
    private Long id;

上面这种办法有个缺点就是,如果有很多的实体类的id都是 long 类型,那就得给每一个都加上注解,这样未免有些麻烦。下面这个方法通过添加一个全局配置来使long类型转为JSON中的string类型,省去了一个一个添加注解的麻烦。

@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;
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。