Jackson Json: How to get multiple values with same name from json node java

2.9k Views Asked by At

I have a Json String that looks like this:

{
 "generatedList1":{"myList":["1","2","3","4"]},
 "generatedList2":{"myList":["1","6","8","2"]},
 "generatedList3":{"myList":["1","12","3","11"]}
}

I want to collect all the values that are there in all of myList i.e. [1,2,3,4,6,8,11,12]

I converted the string to JsonNode and then did JsonNode.findValues("myList") which returns List<JsonNode>. But when I try to convert each JsonNode to String I get double quotes and square brackets as part of the String and not just numbers. I can remove that from the String but it seems hacky. I am sure there has to be a direct way to do this. Any help will be highly appreciated.

1

There are 1 best solutions below

2
On

Here, JsonNode.findValues("myList") returns a List of JsonNode.

You can iterate on each of these JsonNode objects and convert them into List<Integer> easily by:

ObjectMapper mapper = new ObjectMapper();
List<Integer> list = mapper.readerFor(new TypeReference<List<Integer>>(){}).readValue(jsonNode);

You can then combine these lists of Integers to find the unique integers present.