Tobia
Tobia

Reputation: 9526

Spring JSON and 406 HTTP error

i find a lot of questions about this problem but i did not solve... I have this method:

@RequestMapping(value="/testInit")
public @ResponseBody Output test() throws Exception {
    return new Output(true);
}

and i had jackson libreary to classpath, into applicationContext but i still get 406 error with this jquery call:

$.ajax({
    url: "/testInit",
    type: "get",
    dataType: "json"
}); 

Upvotes: 2

Views: 3284

Answers (5)

Adam
Adam

Reputation: 36743

I had this problem, finally tracked down to not having any getters on the class I was using.

i.e. this caused a 406

public static class Pojo {
    private int x;
    public Pojo(int x) {
        this.x = x;
    }
}

But this didn't

public static class Pojo {
    private int x;
    public Pojo(int x) {
        this.x = x;
    }
    public int getX() {
        return x;
    }
}

Yes I was using a class called Pojo :) - I was just doing a dummy example to check Jackson was working in my new setup

Upvotes: 0

Thomas Abraham
Thomas Abraham

Reputation: 356

You have to add the jars and also add org.springframework.http.converter.json.MappingJacksonHttpMessageConverter and org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter to DispatcherServlet-servlet.xml

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter"/>
        </list>
    </property>
</bean>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>

like shown above.

Upvotes: 4

bluesman
bluesman

Reputation: 2260

The only way I could get mine to work was upgrade spring to 3.1 and add a produces to the request mapping.

@RequestMapping(value = "/rest/{myVar}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public MyObject get(
        @PathVariable String myVar) {

None of the other solutions worked for me

Upvotes: 0

Tobia
Tobia

Reputation: 9526

I solved using jackson-all.1.9.0.jar instead of jackson 2 libraries.

Upvotes: 0

Vidar S. Ramdal
Vidar S. Ramdal

Reputation: 1242

The 406 Not Acceptable response is used when the client has requested a content type that the server cannot return. In other words, your client (e.g. the web browser) is sending an Accept header that does not match the server's capabilities.

I'm guessing that the jQuery Ajax method uses the dataType field when setting the Accept header. json is not a well-known content type - but application/json is.

Try replacing dataType: "json" with dataType: "application/json".

Upvotes: 0

Related Questions