如何使用 Spring WebClient get 从端点接收 Map<String, Integer>?
How to receive a Map<String, Integer> from an endpoint using Spring WebClient get?
如何在 Spring 引导中使用 WebClient 从端点 Web 服务接收 Map?这是我的尝试:(它给出了语法错误:Incompatible equality constraint: Map<String, Integer> and Map
)。我该如何解决?
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(Map.class);
}
对于泛型类型,如 Map,您应该在调用 bodyToFlux 方法时使用 ParameterizedTypeReference 而不是 class:
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<>() {});
}
实际上,您可能希望为类型引用定义一个常量:
private static final ParameterizedTypeReference<Map<String, Integer>> MAP_TYPE_REF = new ParameterizedTypeReference<>() {};
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(MAP_TYPE_REF);
}
如何在 Spring 引导中使用 WebClient 从端点 Web 服务接收 MapIncompatible equality constraint: Map<String, Integer> and Map
)。我该如何解决?
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(Map.class);
}
对于泛型类型,如 Map,您应该在调用 bodyToFlux 方法时使用 ParameterizedTypeReference 而不是 class:
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<>() {});
}
实际上,您可能希望为类型引用定义一个常量:
private static final ParameterizedTypeReference<Map<String, Integer>> MAP_TYPE_REF = new ParameterizedTypeReference<>() {};
public Flux<Map<String, Integer>> findAll(String param1, String param2) {
return webClient.get()
.uri(uriBuilder -> uriBuilder
.path("/url")
.queryParam("param1", param1)
.queryParam("param2", param2)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(MAP_TYPE_REF);
}