2

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;
}

}

1 Answer 1

1

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;
        
       ...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I knew there has to be a cleaner way to achieve this. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.