我在 springmvc 框架中处理 reponses 的 json 解码,并使用 jackson 转换器作为实现。 现在有一个案例。有些对象很大,层次很深,我想为此获取最底层的信息。 有没有像 jsonPath 这样的方法通过注释字段或类似的东西来帮助我?
最佳答案
最简单的方法之一是使用“at”函数将根移动到指定的 JSON 节点。
在下面的示例中,我将根节点移到了 node3
。我添加了如何将 node3
转换为简单 POJO 的示例。您也可以直接访问子节点,而无需将其转换为 POJO。
private static final String JSON = "{\"node1\": {\"node2\": {\"node3\": {\"title2\":\"test\"}}}}";
public static void main(String []args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(JSON);
JsonNode node = root.at("/node1/node2");
System.out.println(node);
System.out.println("-----------------");
JsonNode node3 = node.at("/node3");
System.out.println(node3);
System.out.println(node3.asText());
System.out.println("-----------------");
Node result = mapper.readValue(node3.toString(), Node.class);
System.out.println(result);
}
请注意,at
方法永远不会返回 null!
来自方法 javadoc:
Method will never return null; if no matching node exists,
will return a node for which {@link #isMissingNode()} returns true.
如果您发布 JSON 示例并让我了解您想要忽略哪些节点以及您想要解析哪些节点,我可以给出与您的问题更相关的答案。
关于java - Jackson是否支持JsonPath注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36674131/