我想使用Spring和Jackson来使用RESTful WS。 我正在考虑使用Facebook Graph(FC Juventus's JSON data-stream)
获取的JSON流这是我的控制者:
@Controller
public class ConsumeWSController {
@RequestMapping(value = "/consumews", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Consume a RESTful webservice.", locale);
RestTemplate restTemplate = new RestTemplate();
Page page = restTemplate.getForObject("http://graph.facebook.com/juventus", Page.class);
model.addAttribute("pageAbout", page.getAbout());
model.addAttribute("pageAwards", page.getAwards());
return "consumews";
}
}
和Page类:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Page {
private String about;
private String awards;
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public String getAwards() {
return awards;
}
public void setAwards(String awards) {
this.awards = awards;
}
}
但控制台会返回此错误:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [my.proj.Page] and content type [application/json;charset=UTF-8]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
如何解决此错误?
答案 0 :(得分:0)
确保已将正确的Jackson包添加到类路径中。对于Jackson 2
,您使用Maven:
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.3.1</version>
</dependency>
或者如果您使用旧的Jackson
添加:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
答案 1 :(得分:0)
您需要将Jackson定义为JSON
内容的默认邮件转换器。这就是我所做的(我使用GSON,因此这可能不是Jackson消息转换器的确切语法):
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
但是既然你没有将RestTemplate
定义为Spring管理的bean,你需要手动完成:
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
PS。我看到你正在使用较新的Jackson依赖,因此在这种情况下,正确的映射器可能会有所不同。