I am using Jackson (version 2.6+) to parse some ugly JSON that looks like this:
{
"root" : {
"dynamic123" : "Some value"
}
}
The name of the attribute dynamic123
is unfortunately not known until runtime and may differ from time to time. What I am trying to achieve is to use JsonPointer to get to the value "Some value"
. JsonPointer uses an XPath-like syntax that is described here.
// { "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
So, now to my question. Is there a way of retrieving the value "Some value"
using JsonPointer?
Obviously there are other ways of retrieving the value. One possible approach is to use the JsonNode
traversal functions – e.g. like this:
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
But, I am trying to avoid traversal and only use JsonPointer.