简体   繁体   中英

Get element from JsonNode array

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM