[英]What happend to HttpMessageConverters in spring boot 2?
[英]Using JSON HttpMessageConverters with Spring Boot
我正在尝试使用HTTPMessageConverters在调用我的API时将JSON输入转换为对象。 但是,当我尝试将API输入映射到POJO时,看到一条错误消息。 给出错误消息后,我认为该问题与CreateUserRequest类的实现有关。 任何建议将不胜感激! 请看下面:
错误信息:
{
"timestamp": 1515127031483,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "Could not read document: Cannot construct instance of `com.api.service.request.CreateUserRequest`, problem: email\n at [Source: (PushbackInputStream); line: 6, column: 1]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.api.service.request.CreateUserRequest`, problem: email\n at [Source: (PushbackInputStream); line: 6, column: 1]",
"path": "/create"
}
API输入:
curl -X PUT \
http://localhost:8080/create \
-H 'authorization: Basic Ymx1bWV3OjEyMw==' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{
"CreateUserRequest" : {
"email" : "--REDACTED--",
"password" : "--REDACTED--"
}
}'
API控制器:
@RestController
public class BaseActivity {
@RequestMapping(path = "/create", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody String createUser (final @RequestBody CreateUserRequest createUserRequest) { ... }
WebConfig:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {"com.api.service"})
public class ActivityConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
converters.add(mappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
@Bean
public MappingJackson2HttpMessageConverter
mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new
MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonConverter.setObjectMapper(objectMapper);
return jsonConverter;
}
}
请求对象:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreateUserRequest implements Serializable {
private static final long serialVersionUID = 4260711945094777831L;
@NonNull
private String email;
@NonNull
private String password;
}
您的RequestBody是这样的
{
"CreateUserRequest" : {
"email" : "--REDACTED--",
"password" : "--REDACTED--"
}
}
但是我认为应该是这样的:
{
"email" : "--REDACTED--",
"password" : "--REDACTED--"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.