Lombok @NonNull空检查强制实施不适用于Jackson反序列化

时间:2019-02-19 19:56:34

标签: java json jackson lombok

我有一个简单的情况,我想在Java8中使用Jackson(2.8)和Lombok(最新版本)将JSON字符串转换为POJO时,对JSON字符串中的值强制执行空检查。但是看起来Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found at javafx.scene.image.Image.validateUrl(Image.java:1100) at javafx.scene.image.Image.<init>(Image.java:608) at Gui.SignUp.UserInfoFormController.chooseProfilePicture(UserInfoFormController.java:278) 不会在使用@NonNull创建pojo时抛出异常,但是当正常使用构建器模式创建pojo时,它可以正常工作。

这是我的情况:

ObjectMapper.convertValue

2 个答案:

答案 0 :(得分:2)

我看到您找到了一个明显的解决方案。顺便说一句,您可以通过在setter上设置ObjectMapper可见性来解决此问题。查看完整示例。当Lombok生成字节码时,null检查位于设置器中,因此您可以告诉Jackson使用它们。

public class Main {
    public static void main(final String[] args) throws IOException {
        final String v = "{\"name\":\"YourName\",\"surname\":\"YourSurname\"}";
        final ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibilityChecker(
                mapper.getSerializationConfig().getDefaultVisibilityChecker()
                      .withGetterVisibility(Visibility.PUBLIC_ONLY)
                      .withSetterVisibility(Visibility.PUBLIC_ONLY)
        );

        final JsonNode jsonNode = mapper.readValue(v, JsonNode.class);
        System.out.println(jsonNode);

        final User user = mapper.convertValue(jsonNode, User.class);
        System.out.println(user);
    }

    private static class User {
        private String name;
        private String surname;

        public String getName() {
            return name;
        }

        public void setName(final String name) {
            if (name == null) {
                throw new NullPointerException();
            }

            this.name = name;
        }

        public String getSurname() {
            return surname;
        }

        public void setSurname(final String surname) {
            if (surname == null) {
                throw new NullPointerException();
            }

            this.surname = surname;
        }
    }
}

答案 1 :(得分:1)

找到了。通过使用JsonDeserialize批注

进行了修复

  @NoArgsConstructor
  @AllArgsConstructor
  @Builder(builderClassName = "Builder", toBuilder = true)
  @Data
  @JsonDeserialize(builder = MySimplePojo.Builder.class)
  public static class MySimplePojo {
    @NonNull
    private String var1;
    @NonNull
    private List<String> var2;

    @JsonPOJOBuilder(withPrefix = "")
    public static class Builder {
    }
  }