我使用Jackson(版本2.6+)来解析一些看起来像这样的丑陋的 JSON:
{
"root" : {
"dynamic123" : "Some value"
}
}
遗憾的是,属性dynamic123
的名称在运行时才会知道,并且可能会不时发生变化。我想要实现的是使用JsonPointer来获取值"Some value"
。 JsonPointer使用类似 XPath 的语法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
所以,现在回答我的问题。有没有办法使用JsonPointer检索值"Some value"
?
显然还有其他方法可以检索该值。一种可能的方法是使用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。
答案 0 :(得分:1)
我不认为the JsonPointer specification支持通配符。这很基本。相反,您可以考虑将JsonPath与杰克逊地图提供商一起使用。这是一个例子:
public class JacksonJsonPath {
public static void main(String[] args) {
final ObjectMapper objectMapper = new ObjectMapper();
final Configuration config = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
// { "root" : { "dynamic123" : "Some value" } }
ObjectNode json = objectMapper.createObjectNode();
json.set("root", json.objectNode().put("dynamic123", "Some value"));
final ArrayNode result = JsonPath
.using(config)
.parse(json).read("$.root.*", ArrayNode.class);
System.out.println(result.get(0).asText());
}
}
输出:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Some value