在这里,我试图更新一个对象,并在Spring REST控制器中以JSON格式返回更新后的对象。
控制器:
@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类:
@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.发布于 2020-10-08 00:19:08
您混合了JAX-RS和Spring MVC注释:@RequestMapping来自Spring,@Produces来自JAX-RS。如果你看一下@RequestMapping的documentation,你会看到它有一个produces参数,所以你应该有类似这样的东西:
@RequestMapping(value = "/user/revert", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON)
public ResponseEntity<UserResponse> revertUserData(@RequestParam(value = "userName") String userName){
...
}https://stackoverflow.com/questions/64243320
复制相似问题