RestTemplate使用:如何更优雅的接收泛型数据?

时间:2025-04-03 10:17:32

服务提供方:

@RequestMapping(path = "...")
public MessageBox<Map<String, Object>> testReceive(...) {...}

请求类型、接口地址以及接口内部逻辑都不重要,重要的是接口返回的是泛型数据 MessageBox<Map<String, Object>>

服务调用方:

@PostMapping("...")
public void dealWithGenericData(...) {
    ...
        
    String url = ...;
    HttpEntity<String> fromEntity = ...;
    
    // 处理泛型数据 ⭐
    ParameterizedTypeReference<MessageBox<Map<String, Object>>> typeReference = new ParameterizedTypeReference<MessageBox<Map<String, Object>>>() {};
   
    // 发送请求 
    ResponseEntity<MessageBox<Map<String, Object>>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, fromEntity, typeReference);

    // 处理响应信息
    MessageBox<Map<String, Object>> body = responseEntity.getBody();
    log.info(String.valueOf(body));
}

相关源码

	/**
	 * Execute the HTTP method to the given URI template, writing the given
	 * request entity to the request, and returns the response as {@link ResponseEntity}.
	 * The given {@link ParameterizedTypeReference} is used to pass generic type information:
	 * <pre class="code">
	 * ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt; myBean = new ParameterizedTypeReference&lt;List&lt;MyBean&gt;&gt;() {};
	 * ResponseEntity&lt;List&lt;MyBean&gt;&gt; response = (&quot;&quot;,, null, myBean);
	 * </pre>
	 * @param url the URL
	 * @param method the HTTP method (GET, POST, etc)
	 * @param requestEntity the entity (headers and/or body) to write to the request
	 * (may be {@code null})
	 * @param responseType the type of the return value
	 * @return the response as entity
	 * @since 3.2
	 */
	<T> ResponseEntity<T> exchange(
	               URI url, 
	               HttpMethod method, 
	               HttpEntity<?> requestEntity,
	               ParameterizedTypeReference<T> responseType) throws RestClientException;

The given ParameterizedTypeReference is used to pass generic type information