Home > Back-end >  Get List of JSON Objects with WebClient
Get List of JSON Objects with WebClient

Time:06-22

I'm trying to improve my async java skills using Webclient. I have this simple controller that fetch and api but It won't map the response by simply doing "bodyToMono(SportResponse.class)"

I've created this messy private method in order to map the Object and I'm wondering is there is a cleaner way to approach this. THE CURRENT CODE IS WORKS IT JUST LOOKS MESSY AND NOT CLEAN.

@Service
public class SportService {
    private final WebClient sportWebClient;
    private ApplicationConfiguration applicationConfiguration;

public SportService(WebClient webClient, ApplicationConfiguration applicationConfiguration) {
    this.sportWebClient = webClient;
    this.applicationConfiguration = applicationConfiguration;
}

public List<SportResponse> getAllSports() {
    return sportWebClient
            .get()
            .uri("api/v1/json/2/all_sports.php")
            .retrieve()
            .bodyToMono(LinkedHashMap.class)
            .map(this::mapResponse)
            .block();
}
private List<SportResponse> mapResponse(LinkedHashMap response) {
    ObjectMapper mapper = new ObjectMapper();
    List list = (ArrayList) response.get("sports");
    List<SportResponse> sportResponseList = (List<SportResponse>) list.stream()
            .map(item -> mapper.convertValue(item, SportResponse.class))
            .collect(Collectors.toList());
    return sportResponseList;
}

}

CodePudding user response:

You just need to define corresponding POJO using embedded object and Jackson will do mapping automatically

public List<SportResponse.Sport> getAllSports() {
    return sportWebClient
            .get()
            .uri("api/v1/json/2/all_sports.php")
            .retrieve()
            .bodyToMono(SportResponse.class)
            .map(SportResponse::getSports)
            .block();
}

@Data
private class SportResponse {
    @JsonProperty("sports")
    private List<Sport> sports;

    @Data
    private static class Sport {
        @JsonProperty("idSport")
        private String idSport;
        
       ...
    }
}
  • Related