我在springmvc框架中研究响应的json解码,并使用jackson converter作为实现。现在有了一个案例。有些物体很大,有很深的层次,我想要获取最底层的信息。有没有像jsonPath这样的方法,通过注释字段或类似的方法来帮助我呢?
发布于 2016-04-18 05:00:39
最简单的方法之一是使用'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示例,并告诉我您希望忽略哪些节点以及您希望解析哪些节点,我可以给出一个与您的问题更相关的答案。
https://stackoverflow.com/questions/36674131
复制相似问题