2 changed files with 60 additions and 0 deletions
@ -0,0 +1,36 @@ |
|||
package com.bnyer.system.config; |
|||
|
|||
import com.bnyer.system.serializer.LongToStringSerializer; |
|||
import com.fasterxml.jackson.databind.DeserializationFeature; |
|||
import com.fasterxml.jackson.databind.ObjectMapper; |
|||
import com.fasterxml.jackson.databind.module.SimpleModule; |
|||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; |
|||
import org.springframework.context.annotation.Bean; |
|||
import org.springframework.context.annotation.Configuration; |
|||
import org.springframework.context.annotation.Primary; |
|||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; |
|||
|
|||
/** |
|||
* 解决雪花Id长度超过16位前端传入精度丢失的问题 |
|||
*/ |
|||
@Configuration |
|||
public class JsonConfig { |
|||
@Bean |
|||
@Primary |
|||
@ConditionalOnMissingBean(ObjectMapper.class) |
|||
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) |
|||
{ |
|||
ObjectMapper objectMapper = builder.createXmlMapper(false).build(); |
|||
// 全局配置序列化返回 JSON 处理
|
|||
SimpleModule simpleModule = new SimpleModule(); |
|||
//JSON Long ==> String
|
|||
//自定义字符串转化规则ToStringSerializer换成自定义的LongToStringSerializer
|
|||
simpleModule.addSerializer(Long.class, LongToStringSerializer.instance); |
|||
simpleModule.addSerializer(Long.TYPE, LongToStringSerializer.instance); |
|||
|
|||
objectMapper.registerModule(simpleModule); |
|||
//参数在bean中没有的情况处理
|
|||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); |
|||
return objectMapper; |
|||
} |
|||
} |
|||
@ -0,0 +1,24 @@ |
|||
package com.bnyer.system.serializer; |
|||
|
|||
import com.fasterxml.jackson.core.JsonGenerator; |
|||
import com.fasterxml.jackson.databind.JsonSerializer; |
|||
import com.fasterxml.jackson.databind.SerializerProvider; |
|||
|
|||
import java.io.IOException; |
|||
|
|||
public class LongToStringSerializer extends JsonSerializer<Long> { |
|||
public static final LongToStringSerializer instance = new LongToStringSerializer(); |
|||
|
|||
@Override |
|||
public void serialize(Long id, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { |
|||
if(id != null){ |
|||
//长度小于某个值的,还是保持long类型
|
|||
if(id < 10000000000000000L){ |
|||
jsonGenerator.writeNumber(id); |
|||
}else { |
|||
//长度超过某个值的,转化为字符串
|
|||
jsonGenerator.writeString(id.toString()); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
Loading…
Reference in new issue