0

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?

  • Your colors not just simple strings. They are arrays. Try to read the first element of the `Pink` array. – zappee Feb 03 '21 at 10:23

2 Answers2

0

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

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);
        }
    }
D_J
  • 55
  • 2
  • 10