因JS精准度问题,最多表示2^53-1的数值。

新增Long类型序列化的时候,自动会转换为字符串类型规则
This commit is contained in:
hexiaowu 2021-03-12 18:07:53 +08:00
parent 4e5430b5c0
commit fe31d61de9
2 changed files with 36 additions and 1 deletions

View File

@ -1,7 +1,9 @@
package cn.iocoder.dashboard.framework.jackson.config; package cn.iocoder.dashboard.framework.jackson.config;
import cn.iocoder.dashboard.framework.jackson.ser.LongSerializer;
import cn.iocoder.dashboard.util.json.JsonUtils; import cn.iocoder.dashboard.util.json.JsonUtils;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -11,8 +13,15 @@ public class JacksonConfig {
@Bean @Bean
@SuppressWarnings("InstantiationOfUtilityClass") @SuppressWarnings("InstantiationOfUtilityClass")
public JsonUtils jsonUtils(ObjectMapper objectMapper) { public JsonUtils jsonUtils(ObjectMapper objectMapper) {
SimpleModule simpleModule = new SimpleModule();
/*
* 新增Long类型序列化规则数值超过2^53-1在JS会出现精度丢失问题因此Long自动序列化为字符串类型
*/
simpleModule.addSerializer(Long.class,LongSerializer.getInstance())
.addSerializer(Long.TYPE,LongSerializer.getInstance());
objectMapper.registerModule(simpleModule);
JsonUtils.init(objectMapper); JsonUtils.init(objectMapper);
return new JsonUtils(); return new JsonUtils();
} }
} }

View File

@ -0,0 +1,26 @@
package cn.iocoder.dashboard.framework.jackson.ser;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
/**
* Long类型序列化规则
* <p>
* 数值超过2^53-1在JS会出现精度丢失问题因此Long自动序列化为字符串类型
*/
public class LongSerializer extends JsonSerializer<Long> {
private static final LongSerializer LONG_SERIALIZER = new LongSerializer();
@Override
public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.toString());
}
public static LongSerializer getInstance() {
return LONG_SERIALIZER;
}
}