7

I have this json:

{
    "text":[
        {"a":1},
        {"b":2}
    ]
}

I have this code:

JsonNode jsonNode = (new ObjectMapper()).readTree(jsonString);

//get first element from "text"
//this is just an explanation of what i want

String aValue = jsonNode.get("text")[0]
                        .get("a")
                        .asText();

How I can done that, without mapping it to an object?

Or do something like JsonNode[] array and array[0] represent a and array[1] represent b

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
KunLun
  • 3,109
  • 3
  • 18
  • 65

1 Answers1

17

If you want to explicitly traverse through the json and find the value of a , you can do it like this for the json that you specified.

String aValue = jsonNode.get("text").get(0).get("a").asText();

Finding the value of b would be

String bValue = jsonNode.get("text").get(1).get("b").asText();

You can also traverse through the elements within the text array and get the values of a and b as

for (JsonNode node : jsonNode.get("text")) {
    System.out.println(node.fields().next().getValue().asText());
}

And that would print the below on the console

1
2
Madhu Bhat
  • 13,559
  • 2
  • 38
  • 54
  • I know I can iterate with `for loop`. But I need to get just one element on exact index. `.get(x)` is what I needed. I didn't knew it works on array. Thanks. – KunLun May 29 '20 at 19:06
  • From the Array, I want to get the value of "b", but I don't know the index of that element in the array. How can I achieve it? – Satyam Jan 21 '23 at 10:02