Reputation: 22847
~R
I'm trying to do Spring MVC REST JSON channel with automatic conversion to JSON using Jackson. Although I'm doing everything as recommended in other StackOverflow questions, I'm getting HttpMediaTypeNotAcceptableException
and my beans/lists are not converted to JSON. I'm running the code on Jetty.
I've followed the instruction from UTF-8 encoding problem in Spring MVC, Spring 3.0 making JSON response using jackson message converter and Jackson annotations being ignored in Spring, but none of them enables me to send neither bean nor a List<String>
. Both return HTTP status 406. Only the method returning String succeeds with HTTP 200.
My method is:
@RequestMapping(value = "/list", produces = "text/plain; charset=utf-8")
public @ResponseBody List<String> getList() {
return createList();
}
Spring file:
<context:component-scan base-package="de.myapp.rest" />
<context:annotation-config />
<mvc:annotation-driven />
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>
Adding this section also doesn't help:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:order="1">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
</list>
</property>
</bean>
The request HTTP header is generated by jQuery and looks like that:
Accept application/json, text/javascript, /; q=0.01 Accept-Encoding gzip, deflate Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0
However, I get HTTP 406 with HTML error message, and the following lines in log file:
Resolving exception from handler [public de.myapp.rest.TestBean de.myapp.rest.Test.getList()]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
So the question is, what I'm missing here? Why the jackson converter is not registered/how can I debug it? I'm running the code via jetty:run
. But it should not matter, since Spring is application-server-independent.
Upvotes: 0
Views: 7113
Reputation: 26828
In your @RequestMapping
you have produces = "text/plain"
, but your request header says Accept application/json, text/javascript
. There is no match.
Use either produces="application/json"
or don't use produces
at all. It's main use case is to provide more than one method for the same URL, each producing output in a different format (JSP, JSON, XML ...).
Upvotes: 1