1、局部设置一个序列化器,在哪使用哪添加
例如:在你的pojo类中的一个long类型的字段添加@JsonSerialize
@JsonSerialize(using = Long2StringSerialize.class)
private Long articleId;
再在工具包路径下定义一个序列化器类,使用的时候导入即可
public class Long2StringSerialize extends JsonSerializer<Long> {
@Override
public void serialize(Long aLong, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
//aLong就是原始的数据
if (aLong!=null){
jsonGenerator.writeString(aLong.toString());
}
}
}
2、全局设置,全局设置之后所有的返回给前端的long类型的都转换成返回字符串类型。在微服务的配置文件中添加如下类即可
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;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonConfig {
/**
* Jackson全局转化long类型为String,解决jackson序列化时传入前端Long类型缺失精度问题
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
Jackson2ObjectMapperBuilderCustomizer cunstomizer = new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
//将long类型变成字符串类型
jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
}
};
return cunstomizer;
}
}