由于JavaScript中的number最大值为9007199254740992(最大安全值),而java中Long最大为9223372036854775807L,所以在使用VO,DTO中为Long类型超过js最大值是就会出现值不一致的问题,一般的解决办法是把Long类型序列化成json string类型
方式一: 在VO中Long类型属性增加序列化注解
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
......
// 如果是long需要序列化为String,避免JSON数字溢出
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
方式二:定义一个通用的Long序列化处理器
/*
* Copyright (c) huggingai(huangguoliang) copyright message. 2022-2122. All rights reserved.
*/
package com.huggingai.ai.taskmanager.config;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 所有的Long自动转换为String,编码json最大值溢出
*
* @author hank
*/
@Configuration
public class LongToStringAutoConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance)
.serializerByType(Long.TYPE, ToStringSerializer.instance);
}
}
注意: 使用这种方式所有的VO,DTO中的Long都将序列化为json的string类型,如果某些Long属性需要序列化为json number型需要添加序列化注解:
/*
* Copyright (c) huggingai(huangguoliang) copyright message. 2022-2122. All rights reserved.
*/
package com.huggingai.common.entity.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* 分页信息
*
* @author hank
* @since 2023/1/1 11:58
*/
@ApiModel
@Data
public class PageVO<T> {
@ApiModelProperty(value = "总记录数")
@JsonSerialize(as = Number.class)
private Long total;
@ApiModelProperty(value = "数据列表")
private List<T> records;
@ApiModelProperty(value = "当前页码")
@JsonSerialize(as = Number.class)
private Long current;
@ApiModelProperty(value = "每页条数")
@JsonSerialize(as = Number.class)
private Long size;
@ApiModelProperty(value = "总页数")
@JsonSerialize(as = Number.class)
private Long pages;
}