解決SpringBoot2中前臺Long型數據精度丟失問題

想要解決long類型丟失問題,必要將long類型轉換爲String類型再傳輸,一共有三種解決方案

方案一:註解方式:實體類中增加註解

/** 主鍵ID */
@Id
@GeneratedValue(generator = "ID")
@GenericGenerator(name = "ID", strategy = "assigned")
@Column(insertable = false, name = "ID", nullable = false,length = 64)
@JsonSerialize(using = ToStringSerializer.class)//解決long精度丟失問題
private Long id;

方案二:自定義ObjectMapper (推薦):啓動類中增加配置

@SpringBootApplication
@EnableTransactionManagement
public class Application {

	/**
	 * 解決Jackson導致Long型數據精度丟失問題
	 * @return
	 */
	@Bean("jackson2ObjectMapperBuilderCustomizer")
	public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
		Jackson2ObjectMapperBuilderCustomizer customizer = new Jackson2ObjectMapperBuilderCustomizer() {
			@Override
			public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
				jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance)
						.serializerByType(Long.TYPE, ToStringSerializer.instance);
			}
		};
		return customizer;
	}

	public static void main(String[] args){
		SpringApplication.run(Application.class,args);
	}

}

方案三:配置參數:在yml或properties中增加配置

  jackson:
    generator:
      write_numbers_as_strings: true

該方式會強制將所有數字全部轉成字符串輸出,這種方式的優點是使用方便,不需要調整代碼;缺點是顆粒度太大,所有的數字都被轉成字符串輸出了,包括按照timestamp格式輸出的時間也是如此。不推薦

參考:https://blog.csdn.net/haha_66666/article/details/86494853

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章