【发布时间】:2020-10-07 11:44:44
【问题描述】:
这里我正在尝试更新一个对象并在 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);
}
用户响应类:
@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.
【问题讨论】:
-
这表示没有设置标题。您的
RequestMapping中可能缺少produces。见stackoverflow.com/questions/53513644/… -
无法将 'produces= MediaType.APPLICATION_JSON' 参数解析到控制器。只有标题有
标签: java json spring spring-restcontroller http-error