[英]Jackson parser not failing with JsonParseException for obviously bad json
我正在研究为什么简单的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 run中运行它)
您会看到我的JSON有许多悬空的数组[]。 解析器不在乎它们。
此设置似乎允许的其他垃圾是:
final String json = "{}]]]]";
final String json = "[{},[]]]]]]]]";
final String json = "[{},{}]}}}}";
您会看到,问题也不仅限于悬空]-}同样。
我想知道解析器是否在看到最终要“期望”的东西之后停止寻找东西-而不是消耗所有输入。
有什么想法吗? Bueller?
丰富
你是对的。 对数组反序列化之后(如果是"["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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.