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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With