阻止Jackson中的自动String to Integer转换 [英] Prevent automatic String to Integer conversion in Jackson
本文介绍了阻止Jackson中的自动String to Integer转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的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 converts the String into Integer automatically.
有没有办法避免这种自动转换并拥有杰克逊如果将Integer值定义为String,则失败。
Is there a way to avoid this automatic conversion and have Jackson to fail if the Integer values are defined as String.
推荐答案
我在Jackson github上发现了一些有趣的代码问题。改变了一点,这就是我得到的:
I've found the some interesting code on Jackson github issues. Changed it a little and that's what I got:
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();
}
}
这篇关于阻止Jackson中的自动String to Integer转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文