Search code examples
javaspringspring-boothashmapwebclient

How to get ArrayList out of a Hashmap of Json response?


I'm working with Spring Boot and using WebClient to send requests to OMDb

        WebClient webClient = WebClient.create();
        String search = "batman";
        WebClient.ResponseSpec responseSpec = webClient.get()
                .uri("http://www.omdbapi.com/?apikey=[apikey]&s=" + search +"&type=movie&page=1")
                .retrieve();
//        System.out.println(responseSpec);
        String responseBody = responseSpec.bodyToMono(String.class).map();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> mapper = new LinkedHashMap<>();
        try {
            mapper = objectMapper.readValue((JsonParser) responseSpec, Map.class);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
        List<Movie> movieList = new ArrayList<>();
        System.out.println(mapper.get("Search"));

here's the json response, I just want to get the "Search" and convert it to ArrayList so that I can get the movies one by one

{
    "Search": [
        {
            "Title": "Batman Begins",
            "Year": "2005",
            "imdbID": "tt0372784",
            "Type": "movie",
            "Poster": "https://m.media-amazon.com/images/M/MV5BOTY4YjI2N2MtYmFlMC00ZjcyLTg3YjEtMDQyM2ZjYzQ5YWFkXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg"
        },
        {
            "Title": "Batman v Superman: Dawn of Justice",
            "Year": "2016",
            "imdbID": "tt2975590",
            "Type": "movie",
            "Poster": "https://m.media-amazon.com/images/M/MV5BYThjYzcyYzItNTVjNy00NDk0LTgwMWQtYjMwNmNlNWJhMzMyXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg"
        }
      ...
    ],
    "totalResults": "526",
    "Response": "True"
}

problem is mapper.get("Search") in code is a String but when I run the program, it turns into an ArrayList and shows this error (the "totalResults" and "Response" works fine tho, they're Strings)

class java.util.ArrayList cannot be cast to class java.lang.String

so the result is I can't do use String methods with it but I can't use ArrayList method with it either.


Solution

  • This is because "Search" element in json contains list of maps, and jackson parses is like so on default. You can define your mapper as Map<String,Object> and then cast it to the List like so

        Map<String, Object> mapper = new LinkedHashMap<>();
        //...
        (List<Map<String,String>>)mapper.get("Search")).forEach(System.out::println);
    

    However, the better way would be probably to define the DTO with attributes that you need from json and let jackson to parse it into your object and ignore everything else. Or create your custom deserializer like here for example (https://howtodoinjava.com/jackson/jackson-custom-serializer-deserializer/)