簡體   English   中英

在Spring Boot中使用JSON HttpMessageConverters

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM