Qingjian Wang
Qingjian Wang

Reputation: 165

Does Jackson Support JsonPath Annotation

I was working on reponses' json decoding in springmvc framework and is using jackson converter as the implementation. Now there's a case. some of the objects are huge and with very deep levels, I want to grab the very bottom levels of info for that. Is there a way like jsonPath by annotating the field or something like that that could help me out?

Upvotes: 4

Views: 2258

Answers (1)

Ilya Ovesnov
Ilya Ovesnov

Reputation: 4247

One of the easiest ways to do it is to shift the root to the specified JSON node using 'at' function.

In the example below I shifted the root node to the node3. I've added example of how to convert the node3 into simple POJO. Also you can access child nodes directly without converting it into the 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);
}

Note that at method will never return null! From the method javadoc:

Method will never return null; if no matching node exists, 
will return a node for which {@link #isMissingNode()} returns true.

I can come with an answer that is more relevant for your problem if you post JSON example and give me some idea of what nodes you want to ignore and what node you want to parse.

Upvotes: 3

Related Questions