解决 js 处理 Long 类型数据丢失精度的问题

November 23, 2019

1. 从后端解决的三种方法

1.1 推荐:Spring Boot 自定义 Jackson Object Mapper

官方文档 https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-customize-the-jackson-objectmapper

The context's Jackson2ObjectMapperBuilder can be customized by one or more Jackson2ObjectMapperBuilderCustomizer beans.

添加 Jackson 的自定义类,实现 Jackson2ObjectMapperBuilderCustomizer 接口,将 Long 类型序列化成字符串即可

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Component;

@Component
public class Jackson2ObjectMapperCustomizer implements Jackson2ObjectMapperBuilderCustomizer {

    @Override
    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance)
                .serializerByType(Long.TYPE, ToStringSerializer.instance);
    }

}

1.2 使用 @JsonSerialize 注解

在 Entity 或 DTO 等实体类上,针对 Long 类型的属性添加 @JsonSerialize 注解即可

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.*;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

@Entity
@Getter
@Setter
@ToString
public class User implements Serializable {

    private static final long serialVersionUID = -3008460556955441353L;

    @Id
    @JsonSerialize(using = ToStringSerializer.class)
    private Long id;

    private String username;

    private String password;
}

1.3 Spring Boot 修改 application 配置文件

spring:
  jackson:
    generator:
      write_numbers_as_strings: true