Spring's Json not being resolved with appropriate response

Viewed 35147

I've tried to have a controller in Spring return a JSON response to no avail using the Jackson classes as recommended with 3.0. I've got the jackson jar files(jackson-core-asl-1.5.5.jar & jackson-mapper-asl-1.5.5.jar) in my class path of course.

As for the appconfig.xml entries, I'm not sure I need these. I've put them in there as a last act of desperation before returning to ol' fashion non-json ajax.

In debug, I watch the controller get the request, return the foo and then, in firebug, get a 406.

The error messages are as follows: From the logger when set to debug: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

From the response: (406) The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().

My appconfig.xml is here:

    <!-- Configures support for @Controllers -->
    <mvc:annotation-driven />

    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
    <map>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
  </property>
  <property name="viewResolvers">
    <list>
      <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
      </bean>
    </list>
  </property>
  <property name="defaultViews">
    <list>
      <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
    </list>
  </property>
</bean>
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages"></property>
    </bean>

My controller

@RequestMapping(value="foo/bar", method=RequestMethod.GET)
public @ResponseBody foo getFoo(@RequestParam String fooId) {
    return new foo(fooId); 
}

On the jsp, where the ajax call is made:

function addRow() {
  $.getJSON("foo/bar", {
    fooId: 1
  }, function(data) {
    alert("it worked.");
  });
}

Let me know if there's any more info that is needed.

8 Answers

This question pops up everywhere on the net and I got bitten by it a couple of times. Spring 3.0.6 (and 5 possibly) has some issues in rendering json. Once I changed to 3.1.0.RELEASE version eveyrything worked AS IS. Without any config changes. Things to note is, the return method must have @ResponseBody (as in the example before) and must be in servlet-context.xml or your spring context configuration file.

Related