You may get a HTTP 406 Not Acceptable error while trying to return Java objects from a REST controller.

The server is not able to handle your request because the HTTP header “Accept” does not match with any of the content types it can handle.

In fact, the server might be unable to deliver the response in whatever content-type, some piece of configuration is missing in your project.

Example

Let’s declare a “GET /dogs” method in your Spring @Controller:

@RequestMapping(value = "/dogs", method = RequestMethod.GET)
@ResponseBody
public List getDogs() {
  return this.dogRepository.getAllDogs();
}

Using Spring you have to declare a mapper in order to tell Spring how to convert Java POJO to whatever content type. Let’s say you want to convert your POJOs to JSON, so you have to use a JSON Mapper.

Maven dependencies to add

Spring version = 3.1.2.RELEASE
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>	
Spring version >= 3.1.2 RELEASE
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.6</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>	

Just redeploy your webapp and you’ll be able to get your Java POJO as a JSON object.

Side notes:
  • You can use the class annotation @RestController to avoid adding method annotation @ResponseBody
  • HTTP 406 RFC