如何使用Spring WebClient get从端点接收Map <String,Integer>?

问题描述

如何在Spring Boot中使用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之类的通用类型,应在主体调用方法TobodyToFlux中使用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(new ParameterizedTypeReference<>() {});
}

实际上,您可能想为类型引用定义一个常量:

private static final ParameterizedTypeReference<Map<String,Integer>> MAP_TYPE_REF = new ParameterizedTypeReference<>() {};

public Flux<Map<String,param2)
            .build())
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToFlux(MAP_TYPE_REF);
}