Search code examples
javajsonjacksonjava-streamobjectmapper

How to parse json include map and arraylist in java object


I am using java8 stream api and want to parse one Json file and then uses stream api to get desired output.

Sample Json :

{
  "map1":{
    "Test1":
    [
      "1"
    ],
    "Test2":
    [
      "2",
      "3"
    ]
  },
  "map2":{
    "Test3":[
      "4",
      "5"
    ]
  }
}

java Program : Here assume map is populating json file perfect fine. Now when I am running the following program it throws error at line .flatMap(e -> Stream.of(((Map.Entry)e).getKey())) ).

Map map = objectMapper.readValue("test", Map.class);

ArrayList response = (ArrayList) map.entrySet().stream()
        .flatMap(e -> Stream.of(((Map.Entry)e).getValue()))
        .flatMap(e -> Stream.of(((Map)e).keySet()))
        .flatMap(e -> Stream.of(((Map.Entry)e).getKey()))
        .collect(Collectors.toList());

Error : enter image description here

here I want after procession through stream api it should result.

List of [Test1, Test2, Test3]

can someone see this piece of code or suggest something else if it does not work well.


Solution

  • You can use the object mapper's readValue() method using a TypeReference to create a Map<String, Map<String, List<String>>>, then extract the desired result:

    Collection<String> response = ((Map<String, Map<String, List<String>>>) objectMapper.readValue(sampleJson,
            new TypeReference<Map<String, Map<String, List<String>>>>() {})) 
            .values() // to get a collection of Map<String, List<String>>
            .stream().map(m -> m.keySet()) // to get the key set of the map which has the values we want
            .flatMap(Set::stream) // to flatten the collection of sets 
            .collect(Collectors.toList()); // to collect each value to a list
    

    Output:

    [Test1, Test2, Test3]