我正在使用Jackson(2.6+ 版)解析一些丑陋的 JSON,如下所示:
{
"root" : {
"dynamic123" : "Some value"
}
}
不幸的是,该属性的名称dynamic123
直到运行时才知道,并且可能会不时有所不同。我想要实现的是使用JsonPointer来获取 value "Some value"
。JsonPointer使用此处描述的类似XPath的语法。
// { "root" : { "dynamic123" : "Some value" } }
ObjectNode json = mapper.createObjectNode();
json.set("root", json.objectNode().put("dynamic123", "Some value"));
// Some basics
JsonNode document = json.at(""); // Ok, the entire document
JsonNode missing = json.at("/missing"); // MissingNode (as expected)
JsonNode root = json.at("/root"); // Ok -> { dynamic123 : "Some value" }
// Now, how do I get a hold of the value under "dynamic123" when I don't
// know the name of the node (since it is dynamic)
JsonNode obvious = json.at("/root/dynamic123"); // Duh, works. But the attribute name is unfortunately unknown so I can't use this
JsonNode rootWithSlash = json.at("/root/"); // MissingNode, does not work
JsonNode zeroIndex = json.at("/root[0]"); // MissingNode, not an array
JsonNode zeroIndexAfterSlash = json.at("/root/[0]"); // MissingNode, does not work
所以,现在我的问题。有没有办法"Some value"
使用JsonPointer检索值?
显然,还有其他方法可以检索该值。一种可能的方法是使用JsonNode
遍历函数——例如:
JsonNode root = json.at("/root");
JsonNode value = Optional.of(root)
.filter(d -> d.fieldNames().hasNext()) // verify that there are any entries
.map(d -> d.fieldNames().next()) // get hold of the dynamic name
.map(name -> root.get(name)) // lookup of the value
.orElse(MissingNode.getInstance()); // if it is missing
但是,我试图避免遍历,只使用JsonPointer。