我有这个类来代表用户:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public class UserDto implements Serializable {
private Long id;
private String username;
private String email;
private String password;
private Collection<? extends GrantedAuthority> roles;
public UserDto() {
}
}
}
我想做的是让Spring将下面 Controller 的@RequestBody映射到UserDto:
public class AuthController {
@Autowired
private UserService userService;
@Autowired
private AuthService authService;
@RequestMapping(value = "signup", method = RequestMethod.POST)
public ResponseEntity<?> addUser(@RequestBody UserDto userDto) throws Exception {
UserDto existingUserDto;
try {
existingUserDto = userService.save(userDto);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(existingUserDto, HttpStatus.CREATED);
}
}
但是当我尝试发送 Post 请求时,我从 Spring 收到以下错误:
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'username': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@2c477da6; line: 1, column: 10]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'username': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@2c477da6; line: 1, column: 10]
我试图做的是声明一个自定义 MappingJackson2HttpMessageConverter 但我没有得到任何不同的结果
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonConverter.setObjectMapper(objectMapper);
return jsonConverter;
}
这是我正在执行的请求的屏幕(内容类型:application/json):
你有什么想法吗?
最佳答案
能否将您的 Controller 方法 @RequestMapping
更改为以下内容。
@RequestMapping(value = "", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
此外,您不需要添加自定义 MappingJackson2HttpMessageConverter
来完成此操作。还要确保您的 Controller 中注释了正确的请求映射。
@Controller
@RequestMapping("/api/users")
同时删除模型类中的以下注释。向所有属性添加 getter 和 setter,同时保留默认构造函数。
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
希望这有帮助。快乐编码!
关于java - Spring Boot HttpMessageNotReadableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41970869/