Spring Boot 2.0版本 Jackson全局转化long类型为String,解决jackson序列化时long类型缺失精度问题

说明

在传递long类型到前台时,如果long类型的数值比较长,会出现精度丢失的问题。以下是解决办法。

前提

  1. 版本:Spring Boot 2.0及以上
  2. 序列化工具Jackson

解决办法

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;

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

/**
 * Jackson配置
 * @author William
 *
 */
@Configuration
public class JacksonConfig {

	/**
	 * Jackson全局转化long类型为String,解决jackson序列化时long类型缺失精度问题
	 * @return Jackson2ObjectMapperBuilderCustomizer 注入的对象
	 */
	@Bean
	public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
		Jackson2ObjectMapperBuilderCustomizer cunstomizer = new Jackson2ObjectMapperBuilderCustomizer() {
			
			@Override
			public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {

				jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringSerializer.instance);
			}
		};
		
		return cunstomizer;
	}
}

其他配置,参考:https://blog.csdn.net/xiaoxiangzi520/article/details/76522242

你可能感兴趣的:(Spring,Boot从无到有)