阻止Jackson中的自动String to Integer转换

Luc*_*ano 7 java json jackson

我有一个简单的POJO:

public class ADate {
    private Integer day;
    private Integer month;
    private Integer year;
    ... // getters/setters/constructor
}
Run Code Online (Sandbox Code Playgroud)

以下JSON文档被正确反序列化为ADate:

{ 
  "day":"10", 
  "month":"2", 
  "year":"1972"
}
Run Code Online (Sandbox Code Playgroud)

Jackson自动将String转换为Integer.

有没有办法避免这种自动转换,如果将Integer值定义为String,则让Jackson失败.

xen*_*ros 5

我在 Jackson github issues上发现了一些有趣的代码。稍微改变一下,这就是我得到的:

public class ForceIntegerDeserializer extends JsonDeserializer<Integer> {

    @Override
    public int deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        if (jsonParser.getCurrentToken() != JsonToken.VALUE_NUMBER_INT) {
            throw deserializationContext.wrongTokenException(jsonParser, JsonToken.VALUE_STRING, "Attempted to parse String to int but this is forbidden");
        }
        return jsonParser.getValueAsInt();
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

ObjectMapper 上有一个配置设置,称为MapperFeature.ALLOW_COERCION_OF_SCALARS. 如果设置为false,它将阻止 ObjectMapper 将数字和布尔值的字符串表示强制转换为它们的 Java 对应物。只允许严格的转换。

确切的用法示例:

objectMapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);
Run Code Online (Sandbox Code Playgroud)

参考:

[1]添加MapperFeature.ALLOW_COERCION_OF_SCALARS启用/禁用强制 #1106https : //github.com/FasterXML/jackson-databind/issues/1106

[2]防止int从空字符串强制转换为nullif DeserializationFeature .FAIL_ON_NULL_FOR_PRIMITIVESis true#1095: https : //github.com/FasterXML/jackson-databind/issues/1095

[3] ALLOW_COERCION_OF_SCALARS http://fasterxml.github.io/jackson-databind/javadoc/2.9/