自定义反序列化器可将字符串映射到布尔值

我正在通过RestTemplate进行外部呼叫,如下所示:

ResponseEntity<Response> response = template.exchange("some.endpoint.com", HttpMethod.POST, request, MyClass.class);

API以String格式返回布尔值,如下所示:(“ 0”或“ 1”)

{
    "some_lengthy_key_name" : "1"
}

我正在尝试将此响应映射到以下类。

@Getter
@Setter
public class MyClass{
    @JsonProperty("some_lengthy_key_name")
    private boolean isValid;
}

看来杰克逊对此不屑一顾,并引发以下错误(可理解):

无法仅从字符串“ 1”反序列化布尔类型的值,只有“ true”   或“假”识别。

我不想沿途将其捕获为String,然后再修改值。 取而代之的是选择继续进行自定义反序列化的选项,然后进行以下操作:

public class Deserializer extends JsonDeserializer<Boolean> {
    @Override
    public Boolean deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return !"0".equals(parser.getText());
    }
}

现在,我对MyClass中的字段进行了注释,如下所示:

@Getter
@Setter
public class MyClass{
    @JsonDeserialize(using = Deserializer.class)
    @JsonProperty("some_lengthy_key_name")
    private final boolean isValid
}

但是不幸的是,这也不起作用,并抛出相同的错误。 关于这种自定义反序列化的错误之处,我能得到一些建议吗?谢谢。

评论
  • Ben
    Ben 回复

    You can not use final, and use a Boolean type instead of boolean

    @Getter
    @Setter
    public class MyClass{
        @JsonDeserialize(using = Deserializer.class)
        @JsonProperty("some_lengthy_key_name")
        private Boolean isValid; //<= You did not use final, and use Boolean type instead of boolean
    }
    
  • tut
    tut 回复

    You don't need any custom deserializer for this, just override the property with custom setter method and then annotated that method with @JsonProperty. Another note jackson uses getters and setters for serialization and deserialization so you cannot declare variables as final

    @Getter
    @Setter
    class MyClass{
    
       private boolean isValid;
    
       @JsonProperty("some_lengthy_key_name")
       public void setIsValid(String value) {
          isValid = "1".equals(value);
       }
    }