我正在研究为什么简单的Jackson JSON反序列化设置在我明显损坏的Json上不会失败的原因。在我的应用程序中,在映射到Java类型之前,我必须确认输入是有效的json。
final String json = "[\"plop\"]]]]]]]]]]]]]]]]";
final ObjectMapper om = new ObjectMapper();
final JsonFactory jf = new JsonFactory();
jf.setCodec(om);
final JsonParser jp = jf.createParser(json);
jp.disable(JsonParser.Feature.ALLOW_TRAILING_COMMA);
jp.readValueAsTree()
(我在IntelliJ Evaluate中运行它)
您看到我的JSON却有许多我选择的悬空数组close]。解析器不在乎它们。
此设置似乎允许的其他垃圾是:
final String json = "{}]]]]";
final String json = "[{},[]]]]]]]]";
final String json = "[{},{}]}}}}";
您知道,问题也不仅仅限于悬而未决-}的问题。
我想知道解析器是否在看到最终要“预期”的东西之后停止寻找东西-而不是消耗所有输入。
有什么主意吗? Bueller?
丰富
答案 0 :(得分:1)
你是对的。反序列化数组后(对于"["blah"]]]"
,它会停止并且不会读取其他任何内容,因此您可以在关闭]
之后放入任何内容。
有关详细信息,请参见ObjectMapper.readTree
。
@Override
public <T extends TreeNode> T readTree(JsonParser p)
throws IOException, JsonProcessingException
{
/* 02-Mar-2009, tatu: One twist; deserialization provider
* will map JSON null straight into Java null. But what
* we want to return is the "null node" instead.
*/
/* 05-Aug-2011, tatu: Also, must check for EOF here before
* calling readValue(), since that'll choke on it otherwise
*/
DeserializationConfig cfg = getDeserializationConfig();
JsonToken t = p.getCurrentToken();
if (t == null) {
t = p.nextToken();
if (t == null) {
return null;
}
}
JsonNode n = (JsonNode) _readValue(cfg, p, JSON_NODE_TYPE);
if (n == null) {
n = getNodeFactory().nullNode();
}
@SuppressWarnings("unchecked")
T result = (T) n;
return result;
}