spring-webflux:如何在不阻塞的情况下从响应中从 Mono<T> 或 Flux<T> 中提取用户定义的对象?

spring-webflux : How to Extract user defined object from Mono<T> or Flux<T> from the response without blocking?

getUserDetails 方法 returns JsonNode 类型的 Mono。 但我实际上想要 return Mono 或 Flux 请帮助修改 getBulkUserInfo 或 getUserDetails 以获取 Mono< User.java> 或通量

public Mono<JsonNode> getUser(BigInteger Id){
    return this.client.get()
            .uri("/URL/{Id}",Id)
            .retrieve()
            .bodyToMono(JsonNode.class);
}

public Flux getBulkUsers(List<BigInteger> Ids){
    return Flux.fromIterable(Ids).flatMap(this::getUser);
}

但是 Url 的 json 响应类似于

{
"resultholder": {
            "totalResults": "1",
            "profiles": {
                "profileholder": {
                    "user": {
                        "country": "IND",
                        "zipCode": "560048",
                        "name":"Test"
                    }
                }
            }            
        }
}

我尝试了不同的方法,但没有任何效果 subscribe() 和 .doOnNext(resp -> resp.get("resultholder").get("profiles").get("profileholder").get("user"))

    .bodyToMono(JsonNode.class)
.doOnNext(resp ->{return
 JSONUtils.deserialize(resp.get("resultholder").get("profiles").get("profileholder").get("user"), User.class)})

这很简单,没有必要阻止。它只是在响应上应用进一步的映射。您可以使用以下代码解决您的问题

 return webClient
            .get()
            .uri("profilesEndPoint/" + id)
            .retrieve()
            .bodyToMono(JsonNode.class)
            .map(jsonNode ->
                    jsonNode.path("resultholder").path("profiles").path("profileholder").path("user")
            ).map(
                    userjsonNode -> mapper.convertValue(userjsonNode, User.class)
            );

其中mapper是jackson ObjectMapper

private final ObjectMapper mapper = new ObjectMapper();

如果您有任何问题,请参考此代码 here :