Reputation: 3225
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
Upvotes: 8
Views: 35689
Reputation: 15183
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
Upvotes: 21