简体   繁体   中英

Getting HTTP Status 406 – Not Acceptable error when trying to return an object in Spring REST controller

Here i'm trying to update an object and return the updated object in JSON format in a Spring REST controller.

Controller:

@RequestMapping(value = "/user/revert", method = RequestMethod.POST)
@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public ResponseEntity<UserResponse> revertUserData(@RequestParam(value = "userName") String userName) {

    User user = new User();
    UserResponse userResponse = new UserResponse();

    try {
        user = userService.findUserByName(userName);
        user.setLastName(null);

        userResponse.setEmail(user.getEmail());
        userResponse.setLastName(user.getLastName());

    } catch (Exception e) {
        return new ResponseEntity<UserResponse>(userResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<UserResponse>(userResponse, HttpStatus.OK);

}

UserResponse class:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserResponse {

  @JsonProperty("email")
  private String email;
  @JsonProperty("lastName")
  private String lastName;

  //getter and setter methids 

}

pom file:

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

The error im getting:

The target resource does not have a current representation that would be acceptable to the
user agent, according to the proactive negotiation header fields received in the request, and the server is
unwilling to supply a default representation.

You mixed JAX-RS and Spring MVC annotations: @RequestMapping comes from Spring and @Produces from JAX-RS. If you take a look at the @RequestMapping 's documentation you'll see that it has a produces parameter. So you should have something like:

@RequestMapping(value = "/user/revert", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON)
public ResponseEntity<UserResponse> revertUserData(@RequestParam(value = "userName") String userName){
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM