使用 ParameterizedTypeReference 的通用类型 WebClient

问题描述 投票:0回答:1

我调用一个 Web 服务,它根据我作为参数传递的字符串别名返回以下 Json,

if alias is isActive,
 then json response = {isActive=true}
if alias is rolesAlias,
then json response = [{"id":"2","name":"APPROVER","description":"approver"},{"id":"demo","name":"Demo","description":""}]
if alias is actionsAlias,
 then response = [{"id":"approve","name":"APPROVE"}]
if alias is resourcesAlias,
 then response = [{"id":"screen1","name":"screen1","entry_type":"0"}]
if alias is policiesAlias,
 then response = [{"id":"1","name":"XYZ"}]
if alias is groupsAlias,
 then response = [{"id":"1","name":"ABC","description":"New Group"}]

我创建了一个 ResponseEnvelope 类来保存数据,

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

@Builder
@Getter
@Setter
public class ResponseEnvelope<T> {
    private final String apiVersion;    
    private final T data;
    private final List<ErrorResponse> errorResponse;

    public ResponseEnvelope(){
        data = null;
        apiVersion = null;        
        errorResponse = null;
    }

    public ResponseEnvelope(String apiVersion, T data, List<ErrorResponse> err){

        this.apiVersion = apiVersion;        
        this.data = data;
        this.errorResponse = err;
    }
}

我以这种方式调用网络服务,

     public Mono<ResponseEnvelope<String>> callMethod(String alias) throws Exception {
        
            //code to generate url using alias passed as argument
            
            return webClient.get()
              .uri(url.toString())
              .accept(MediaType.APPLICATION_JSON)
              .retrieve()          
              .bodyToMono(new ParameterizedTypeReference<ResponseEnvelope<String>>() {})
          
      }

但是我收到 NullPointerException,因为使用 ParameterizedTypeReference 转换响应时存在一些问题。

我哪里出错了?

拜托,任何建议都会有很大帮助。

java generics spring-webflux spring-webclient
1个回答
0
投票

您缺少带有 @JsonProperty 的字段注释,如果您使用 ParameterizedTypeReference,则这是必需的。

并在编译器插件配置中添加以下代码片段。

<annotationProcessorPaths>
    <path>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
    </path>
</annotationProcessorPaths>
© www.soinside.com 2019 - 2024. All rights reserved.