3

Simply put, how do I retrieve {"value1":123"} using Jackson in a non-chaining way?

{
  "aaa": [
      {
        "value1": "123"
      }
  ],
  "bbb": [
      {
          "value2": "456"
      }
  ]
}

I tried using: jsonNode.at("/aaa[Array][0]) but i get missing node in response.

Any help would be good.

hnvasa
  • 830
  • 4
  • 13
  • 26
  • 1
    Use `ObjectMapper` `ObjectMapper objectMapper = new ObjectMapper(); Map> map = objectMapper.readValue(json, Map.class);` – Hadi J Aug 20 '18 at 04:22
  • 2
    Possible duplicate of [Reading value of nested key in JSON with Java (Jackson)](https://stackoverflow.com/questions/29858248/reading-value-of-nested-key-in-json-with-java-jackson) see the first answer here – Gimhani Aug 20 '18 at 04:25

3 Answers3

6

The correct json path expression would be "/aaa/0/value1"

Use:

jsonNode.at("/aaa/0/value1")
Bwvolleyball
  • 2,593
  • 2
  • 19
  • 31
S.K.
  • 3,597
  • 2
  • 16
  • 31
  • This works OK, but what is the function of the `/0/` in between the nodes? My subfield is not the first index, still this works – Testilla Apr 09 '22 at 15:15
  • `aaa` is a json array, so it has to be followed by an index. – S.K. Apr 09 '22 at 18:02
1

use this below code :

    JsonNode node = mapper.readTree(json);
    System.out.println(node.path("aaa").get(0)); // {"value1":"123"}
  1. use jackson-databind.
  2. use this

    node.path("aaa").get(0).get("value1") // 123.

Ashok Kumar N
  • 573
  • 6
  • 23
1

Using node.path("aaa").get(0) is what retrieved the first item from array. Any other ideas like node.path("aaa[0]") or node.path("aaa/0") do not work.

  • 1
    the question specifically asked for a way of doing it `in a non-chaining way`. Although what you are saying there is correct, and you can definitely do it that way. It is outside of the scope of the question. – AlexT Jan 19 '21 at 12:04