我正在使用Androd resttemplate和MappingJacksonHttpMessageConverter。 对于一些网址交换工作很好,但一个是造成例外。 Resttemplate的实例化
restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
rootUrl = "http://someserver.com"
和交换功能:
public Questions loadQuestQuestions(int quest_id, String token) {
HashMap<String, Object> urlVariables = new HashMap<String, Object>();
urlVariables.put("quest_id", quest_id);
urlVariables.put("token", token);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));
HttpEntity<Object> requestEntity = new HttpEntity<Object>(httpHeaders);
return restTemplate.exchange(rootUrl.concat("/tasks/{quest_id}/questions?token={token}"), HttpMethod.GET, requestEntity, Questions.class, urlVariables).getBody();
}
问题 -
import org.codehaus.jackson.map.annotate.JsonRootName;
import java.util.LinkedList;
/**
* Wrapper for collection
*/
@JsonRootName(value = "questions")
public class Questions extends LinkedList<Question> {
}
Question
包含所有需要的注释,包括@JsonRootName
Json comming有内容类型'application / json',一切都是正确的,最近效果很好。
但抛出异常:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [Questions] and content type [application/json;charset=utf-8]
答案 0 :(得分:1)
我认为您的代码没有任何问题。 Spring 3.2.x增加了使用Jackson 2 MappingJackson2HttpMessageConverter
的转换器。也许你可以试试这个转换器。这解决了我过去遇到的类似问题。确保您的POJO具有Jackson 2注释。希望这能帮到你。
RestTemplate template = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter map = new MappingJackson2HttpMessageConverter();
messageConverters.add(map);
template.setMessageConverters(messageConverters);
MyClass msg = template.postForObject(url, request, MyClass.class);