使用WebClient获取JSON对象列表



我正在尝试使用Webclient来提高我的异步java技能。我有这个简单的控制器来获取和api但它不会通过简单地执行"bodyToMono(SportResponse.class)">

来映射响应我已经创建了这个混乱的私有方法来映射对象,我想知道是否有一个更干净的方法来处理这个问题。当前的代码是工作的,它只是看起来混乱和不干净。

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

}

您只需要使用嵌入式对象定义相应的POJO, Jackson将自动进行映射

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;

...
}
}

相关内容

  • 没有找到相关文章

最新更新