如何使用postForEntity获取MultiValueMap类型的响应?
解决RestTemplate返回MultiValueMap的泛型类型检查问题
问题原因
直接声明ResponseEntity<MultiValueMap<String, Object>>后调用postForEntity报错,是因为MultiValueMap.class丢失了泛型信息,方法返回的实际类型是ResponseEntity<? extends MultiValueMap>,与声明的具体泛型类型不兼容。
解决方案
方案一:使用ParameterizedTypeReference(推荐,类型安全)
利用Spring的ParameterizedTypeReference保留泛型信息,调用exchange方法替代postForEntity:
// 声明带具体泛型的返回对象 ResponseEntity<MultiValueMap<String, Object>> responseEntity; // 使用exchange方法,通过ParameterizedTypeReference指定泛型类型 responseEntity = restTemplate.exchange( serviceURL, HttpMethod.POST, entity, new ParameterizedTypeReference<MultiValueMap<String, Object>>() {} );
这种方式完全符合类型检查规范,不会产生raw type或类型不兼容的问题。
方案二:类型转换+抑制unchecked警告
如果需要继续使用postForEntity,可以通过强制类型转换解决,同时添加注解抑制linter的unchecked警告(需确保接口返回的确实是MultiValueMap<String, Object>类型):
// 声明带具体泛型的返回对象 ResponseEntity<MultiValueMap<String, Object>> responseEntity; // 强制转换并抑制unchecked警告 @SuppressWarnings("unchecked") responseEntity = (ResponseEntity<MultiValueMap<String, Object>>) restTemplate.postForEntity( serviceURL, entity, MultiValueMap.class );
内容的提问来源于stack exchange,提问作者Mikhail T.
相关产品推荐
相关产品推荐

