問題描述
今天遇到了一個很奇怪的問題,spring boot的版本是2.0.9,jackson的版本是2.9.8。
我有個類的成員變量類型是integer,然后前端傳參的時候傳了個浮點數(shù)20.5,在controller獲取到參數(shù)的時候自動截斷為20。
問題解決
有些場景,比如需要參數(shù)校驗,不希望float可以自動截斷,希望快速失敗,所以需要設(shè)置下。
源碼DeserializationFeature這個類,控制反序列化的特性。
可以看到ACCEPT_FLOAT_AS_INT這個特性在2.6后默認(rèn)是true,
/**
* Feature that determines whether coercion from JSON floating point
* number (anything with command (`.`) or exponent portion (`e` / `E'))
* to an expected integral number (`int`, `long`, `java.lang.Integer`, `java.lang.Long`,
* `java.math.BigDecimal`) is allowed or not.
* If enabled, coercion truncates value; if disabled, a {@link JsonMappingException}
* will be thrown.
*<p>
* Feature is enabled by default.
*
* @since 2.6
*/
ACCEPT_FLOAT_AS_INT(true),
所以需要對其的這個設(shè)置進行修改。
在application.yaml文件輸入
spring:
jackson:
deserialization:
ACCEPT_FLOAT_AS_INT: false
重新進行請求
對于integer類型的參數(shù),重新傳浮點數(shù),會報序列化錯誤的失敗,問題解決。