[java] "Could not find acceptable representation" using spring-boot-starter-web

I am trying to use spring-boot-starter-web to create a rest service serving up JSON representations of Java objects. From what I understand this boot-starter-web jar is supposed to handle the conversion to JSON through Jackson automatically but I am instead getting this error.

{ 
  "timestamp": 1423693929568,
  "status": 406,
  "error": "Not Acceptable",
  "exception": "org.springframework.web.HttpMediaTypeNotAcceptableException",
  "message": "Could not find acceptable representation"
}

My Controller is this...

@RestController
@RequestMapping(value = "/media")
public class MediaController {
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public @ResponseBody UploadResult test(@RequestParam(value="data") final String data) {
      String value = "hello, test with data [" + data + "]"; 
      return new UploadResult(value);
    }

    @RequestMapping(value = "/test2", method = RequestMethod.POST)
    public int test2() {
        return 42;
    }

    @RequestMapping(value = "/test3", method = RequestMethod.POST)
    public String test3(@RequestParam(value="data") final String data) {
        String value = "hello, test with data [" + data + "]"; 
        UploadResult upload = new UploadResult(value);
        return upload.value;
    }


    public static class UploadResult {
        private String value;
        public UploadResult(final String value)
        {
            this.value = value;
        }
    }
}

My pom.xml has...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.2.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <version>1.2.1.RELEASE</version>
    <scope>provided</scope>
</dependency>

mvn dependency:tree shows that spring-boot-starter-web does indeed depend on the jackson2.4 databind and thus should be on the classpath...

[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.2.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.2.1.RELEASE:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.8:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.8:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.14:runtime
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.4.4:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.4.0:compile
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.4.4:compile
[INFO] |  +- org.hibernate:hibernate-validator:jar:5.1.3.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.0.0:compile
[INFO] |  +- org.springframework:spring-web:jar:4.1.4.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-aop:jar:4.1.4.RELEASE:compile
[INFO] |  |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  |  +- org.springframework:spring-beans:jar:4.1.4.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-context:jar:4.1.4.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.1.4.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:4.1.4.RELEASE:compile

... yet calling the test service gives the error mentioned above. test2 and test3 work fine proving that it must just be the attempted conversion to JSON that is failing? Am I missing some configuration problem or annotations? From all the examples I can find, annotating the class for basic Jackson JSON conversion is no longer necessary.

Any help greatly appreciated.

This question is related to java json spring maven spring-mvc

The answer is


Had similar issue when one of my controllers was intercepting all requests with empty @GetMapping


Add below dependency to your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.10.2</version>
</dependency>

My return object didn't have @XmlRootElement annotation on the class. Adding the annotation solved my issue.

@XmlRootElement(name = "ReturnObjectClass")
public class ReturnObjectClass {

    @XmlElement(name = "Status", required = true)
    protected StatusType status;
    //...
}

accepted answer is not right with Spring 5. try changing your URL of your web service to .json! that is the right fix. great details here http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html


I was running into the same issue, and what I was missing in my setup was including this in my maven (pom.xml) file.

<dependency>
     <groupId>org.codehaus.jackson</groupId>
     <artifactId>jackson-mapper-asl</artifactId>
     <version>1.9.9</version>
</dependency> 

If you are using Lombok, make sure it have annotations like @Data or @Getter @Setter in your Response Model class.


I had this issue when accessing actuator. Putting following configuration class solved the issue:

@Configuration
@EnableWebMvc
public class MediaConverterConfiguration implements WebMvcConfigurer {
    @Bean
    public MappingJackson2HttpMessageConverter jacksonConverter() {
        MappingJackson2HttpMessageConverter mc =
                new MappingJackson2HttpMessageConverter();
        List<MediaType> supportedMediaTypes =
                new ArrayList<>(mc.getSupportedMediaTypes());
        supportedMediaTypes
                .add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        supportedMediaTypes.add(
            MediaType.valueOf("application/vnd.spring-boot.actuator.v2+json"));
        mc.setSupportedMediaTypes(supportedMediaTypes);
        return mc;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonConverter());
    }
}

For me, the problem was trying to pass a filename in a url, with a dot. For example

"http://localhost:8080/something/asdf.jpg" //causes error because of '.jpg'

It could be solved by not passing the .jpg extension, or sending it all in a request body.


In my case I happened to be using lombok and apparently there are conflicts with the get and set


I had a similar error using spring/jhipster RESTful service (via Postman)

The endpoint was something like:

@RequestMapping(value = "/index-entries/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<IndexEntry> getIndexEntry(@PathVariable Long id) {

I was attempting to call the restful endpoint via Postman with header Accept: text/plain but I needed to use Accept: application/json


I had to explicitly call out the dependency for my json library in my POM.

Once I added the below dependency, it all worked.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

I too was facing a similar issue. In my case the request path was accepting mail id as path variable, so the uri looked like /some/api/[email protected]

And based on path, Spring determined the uri is to fetch some file with ".com" extension and was trying to use different media type for response then intended one. After making path variable into request param it worked for me.


I had the same exception but the cause was different and I couldn't find any info on that so I will post it here. It was just a simple to overlook mistake.

Bad:

@RestController(value = "/api/connection")

Good:

@RestController
@RequestMapping(value = "/api/connection")

I had the same exception. The problem was, that I used the annotation

@RepositoryRestController

instead of

@RestController


I got the exact same problem. After viewing this reference: http://zetcode.com/springboot/requestparam/

My problem solved by changing

method = RequestMethod.GET, produces = "application/json;charset=UTF-8"

to

method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE

and don't forget to add the library:

import org.springframework.http.MediaType;

it works on both postman or regular browser.


If using @FeignClient, add e.g.

produces = "application/json"

to the @RequestMapping annotation


In my case I was sending in correct object in ResponseEntity<>().

Correct :

@PostMapping(value = "/get-customer-details", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> getCustomerDetails(@RequestBody String requestMessage) throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("customerId", "123");
    jsonObject.put("mobileNumber", "XXX-XXX-XXXX");
    return new ResponseEntity<>(jsonObject.toString(), HttpStatus.OK);
}

Incorrect :

return new ResponseEntity<>(jsonObject, HttpStatus.OK);

Because, jsonObject's toString() method "Encodes the jsonObject as a compact JSON string". Therefore, Spring returns json string directly without any further serialization.

When we send jsonObject instead, Spring tries to serialize it based on produces method used in RequestMapping and fails due to it "Could not find acceptable representation".


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to maven

Maven dependencies are failing with a 501 error Why am I getting Unknown error in line 1 of pom.xml? Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Unable to compile simple Java 10 / Java 11 project with Maven ERROR Source option 1.5 is no longer supported. Use 1.6 or later 'react-scripts' is not recognized as an internal or external command How to create a Java / Maven project that works in Visual Studio Code? "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)