was*_*ren 9 java json jackson jsonpointer
我正在使用Jackson(版本 2.6+)来解析一些看起来像这样的丑陋的JSON:
{
"root" : {
"dynamic123" : "Some value"
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
所以,现在我的问题。有没有办法"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
Run Code Online (Sandbox Code Playgroud)
但是,我试图避免遍历并且只使用JsonPointer。
我认为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());
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10085 次 |
最近记录: |