我正在研究为什么简单的 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 = "[{},{}]}}}}";
你看,问题并不局限于悬空 ] - } 也有同样的问题。
我想知道解析器是否在看到“预期”的最终内容后停止寻找内容 - 而不是消耗所有输入。
大家有什么想法吗?布勒?
丰富
最佳答案
你是对的。反序列化数组后(在 "["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;
}
关于java - Jackson 解析器不会因明显错误的 json 而因 JsonParseException 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56056227/