使用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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需要使用嵌入式对象定义相应的POJO,杰克逊将自动进行映射
You just need to define corresponding POJO using embedded object and Jackson will do mapping automatically