0

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.

dopamane
  • 1,315
  • 2
  • 14
  • 27
AB Newbie
  • 1
  • 1
  • 2
  • Please add your actual code to the question (properly formatted with the `{}` button). It sounds like you are using the `JsonNode` directly instead of the `List` that you got. Why? – RealSkeptic Oct 07 '18 at 09:03
  • I was iterating through each node and for each node i was doing mapper.writeValueAsString(node); This String had double quotes and square brackets. Solution by Apoorv worked for me. – AB Newbie Oct 08 '18 at 10:55

1 Answers1

0

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.

Apoorv Agarwal
  • 336
  • 1
  • 7