繁体   English   中英

获取 HTTP 状态 406 – 尝试在 Spring 中返回 object 时出现不可接受的错误 REST controller

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

在这里,我正在尝试更新 object 并以 JSON 格式返回更新后的 object 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);

}

用户响应 class:

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

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

  //getter and setter methids 

}

pom文件:

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

我得到的错误:

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.

您混合了 JAX-RS 和 Spring MVC 注释: @RequestMapping来自@Produces ,@Produces 来自 JAX-RS。 如果您查看@RequestMapping文档,您会发现它有一个produces参数。 所以你应该有这样的东西:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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