我目前正在開發一個 Spring Boot 應用程式,它將外部 REST API 包裝到我自己的 GraphQL API 中。
到目前為止,我已經做了這個方法回傳一個SerieDetails:
public SerieDetails findOrThrow(long id) throws RuntimeException {
try {
return this.webClient
.get()
.uri("/tv/{id}?api_key={apiKey}&language={lang}", id, this.apiKey, this.lang)
.retrieve()
.bodyToMono(SerieDetails.class)
.log()
.block();
} catch(Exception e ) {
throw new RuntimeException("Can't reach the API");
}
}
將此 JSON 轉換為我自己的物件:
{
"id": 71912,
"name": "The Witcher",
"overview": "Geralt of Rivia, a mutated monster-hunter for hire, journeys toward his destiny in a turbulent world where people often prove more wicked than beasts."
"last_air_date": "2019-12-20",
...
}
這很好用。但現在我正在做另一個呼叫,回傳一個SerieDetails給定查詢的串列,它回傳result陣列下的結果:
{
"page": 1,
"results": [
{
"id": 71912,
"name": "The Witcher",
"overview": "Geralt of Rivia, a mutated monster-hunter for hire, journeys toward his destiny in a turbulent world where people often prove more wicked than beasts."
"first_air_date": "2019-12-20",
...
},
{
"id": 106541,
"name": "The Witcher: Blood Origin",
"overview": "Set in an elven world 1200 years before the world of The Witcher, the show charts the origins of the very first Witcher, and the events that lead to the pivotal “conjunction of the spheres,” when the worlds of monsters, men, and elves merged to become one.",
"first_air_date": "2002-09-22",
...
}
]
}
而且我不知道如何使用 WebClient 來實作它。到目前為止我試過這個:
public List<SerieDetails> findByQuery(String query) {
return this.webClient
.get()
.uri("/search/tv?api_key={apiKey}&language={lang}&query={query}", this.apiKey, this.lang, query)
.retrieve()
.bodyToFlux(SerieDetails.class)
.log()
.collect(Collectors.toList())
.block();
}
但它不起作用。
uj5u.com熱心網友回復:
您需要更改 JSON 反序列化到的物件。函式bodyToMono和bodyToFlux創建兩個不同的流,其中Mono和Flux是發布者:
Mono最多發出一項;Flux發出從零到 N 項的序列。
這些專案是指定類的實體。在您的情況下,它是 JSON 回應轉換為SerieDetails. 多個專案并不意味著 的陣列SerieDetails,而是具有SerieDetails.結構的多個 JSON 回應。你可以把這想象成同一個類的不同物件實體。
更簡單的解決方案是創建以下類:
class PaginatedSerieDetails {
private int page;
private List<SerieDetails> results;
// getters and setters
}
然后,當您按如下方式進行呼叫時,您將使用這個:
public List<SerieDetails> findByQuery(String query) {
return this.webClient
.get()
.uri("/search/tv?api_key={apiKey}&language={lang}&query={query}", this.apiKey, this.lang, query)
.retrieve()
.bodyToMono(PaginatedSerieDetails.class)
.map(PaginatedSerieDetails::getResults())
.log()
.block();
}
作為旁注,請.block()在使用 WebFlux 時盡量避免。當你這樣做時,你就違背了使用反應式堆疊的全部目的,因為你是說你想讓執行緒等待 Mono 或 Flux 發出一個值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344083.html
