1. 程式人生 > >Spring Boot 2.0版本 Jackson全域性轉化long型別為String,解決jackson序列化時long型別缺失精度問題

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