11

我正在使用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

4

1 回答 1

5

我不认为JsonPointer 规范支持通配符。这是非常基本的。相反,您可以考虑将JsonPath与 Jackson 映射提供程序一起使用。这是一个例子:

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
于 2016-03-11T22:51:13.020 回答