防止在 Jackson 中自动将字符串转换为整数 [英] Prevent automatic String to Integer conversion in Jackson
问题描述
我有一个简单的 POJO:
I have a simple POJO:
public class ADate {
private Integer day;
private Integer month;
private Integer year;
... // getters/setters/constructor
}
以下 JSON 文档正确反序列化为 ADate
:
The following JSON Document gets deserialized correctly into ADate
:
{
"day":"10",
"month":"2",
"year":"1972"
}
Jackson 自动将字符串转换为整数.
Jackson converts the String into Integer automatically.
如果整数值定义为字符串,有没有办法避免这种自动转换并让杰克逊失败.
Is there a way to avoid this automatic conversion and have Jackson to fail if the Integer values are defined as String.
推荐答案
ObjectMapper 上有一个配置设置,称为 MapperFeature.ALLOW_COERCION_OF_SCALARS
.如果设置为 false
,它将阻止 ObjectMapper 将数字和布尔值的字符串表示强制转换为它们的 Java 对应项.只允许严格转换.
There is a configuration setting on the ObjectMapper called the MapperFeature.ALLOW_COERCION_OF_SCALARS
. If set to false
, it will prevent ObjectMapper from coercing String representations of numbers and booleans into their Java counterparts. Only strict conversions will be allowed.
具体用法示例:
objectMapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);
参考文献:
[1] 添加 MapperFeature.ALLOW_COERCION_OF_SCALARS
以启用/禁用强制转换 #1106:https://github.com/FasterXML/jackson-databind/issues/1106
[1] Add MapperFeature.ALLOW_COERCION_OF_SCALARS
for enabling/disabling coercions #1106: https://github.com/FasterXML/jackson-databind/issues/1106
[2] 如果 DeserializationFeature .FAIL_ON_NULL_FOR_PRIMITIVES
是 true
,则防止将 int
从空字符串强制转换为 null
代码> #1095: https://github.com/FasterXML/jackson-数据绑定/问题/1095
[2] Prevent coercion of int
from empty String to null
if DeserializationFeature .FAIL_ON_NULL_FOR_PRIMITIVES
is true
#1095: https://github.com/FasterXML/jackson-databind/issues/1095
[3] ALLOW_COERCION_OF_SCALARS http://fasterxml.github.io/jackson-databind/javadoc/2.9/
这篇关于防止在 Jackson 中自动将字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!