How to access the value from a key-value pair in a jsonnode

1.3k Views Asked by At

I have got a JsonNode like the below

"{"Pink":["#000000"],"Red":["#000000"],"Blue":["#000000"],"Orange":["#000000"]}"

and I am trying to get the value for Pink for e.g like this

jsonNode.get("Pink").asText()

But this isn't working - is there another way that I can access these values through Java?

2

There are 2 best solutions below

0
On

It looks like your problem here is that "Pink" is an array and not a string. The solution here is to either remove the square brackets, or if that is not possible, the following should give you the expected result:

jsonNode.get("Pink").get(0).asText()
0
On

This method will help you to traverse JsonNode

public void getColorCode() throws JsonProcessingException {
        String color = "{\"Pink\":[\"#000000\"],\"Red\":[\"#000000\"],\"Blue\":[\"#000000\"],\"Orange\":[\"#000000\"]}";

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(color);

        for (JsonNode colorCode : node.get("Pink")){
            System.out.println(colorCode);
        }
    }