如何在 MockMVC 中转换 desearilize 布尔值?

How to convert desearilize boolean in MockMVC?

你好,我的 class 中有一个布尔变量,我试图在我的 spring 启动测试中 post 这个 class。

但是我遇到如下错误:

2020-07-21 03:42:11.590  WARN 11660 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'spbrResponse' on field 'isSuccess': rejected value [null]; codes [typeMismatch.spbrResponse.isSuccess,typeMismatch.isSuccess,typeMismatch.boolean,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spbrResponse.isSuccess,isSuccess]; arguments []; default message [isSuccess]]; default message [Failed to convert value of type 'null' to required type 'boolean'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [null] to type [@com.fasterxml.jackson.annotation.JsonProperty boolean] for value 'null'; nested exception is java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type]]

布尔字段称为 isSuccess,我已经有 getter 和 setter 方法:

public class SpbrResponse<T> {
    private boolean isSuccess;
    private T result;
    private String error;

    public void setIsSuccess(boolean isSuccess) {
        this.isSuccess = isSuccess;
    }    

    public boolean getIsSuccess() {
        return isSuccess;
    }
}

在单元测试中,我使用 ObjectMapper 将对象转换为 JSON:

    ReportGenerationResponse response = new ReportGenerationResponse(1, 1, 1, 1, "xx", "yy", "zz");
    SpbrResponse<ReportGenerationResponse> wrappedResponse = new SpbrResponse<>(true, response, "");

    mockMvc.perform(
            post("/ReportComplete")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(objectMapper.writeValueAsString(wrappedResponse))
    )
    .andExpect(status().isOk());

我也试过用

  1. @JsonProperty
  2. 将 setter 方法重命名为 setSuccess()

但都失败了。非常感谢任何帮助。

正确答案是使用@JsonProperty 注释。我一开始尝试使用它,但方式不对。正确的语法是:

public class SpbrResponse<T> {
    @JsonProperty("isSuccess")
    private boolean isSuccess;
    private T result;
    private String error;
}