当没有Map属性而导致空对象时,是否可以使JacksonObjectMapper反序列化失败?

dphi5xsq  于 2022-11-08  发布在  其他
关注(0)|答案(3)|浏览(128)

我在纠结一个问题:是否可以将Jackson配置为在没有Map字段时抛出错误?
范例:还原序列化空对象(“{}”),或不含目的对象所包含的任何字段。

y1aodyip

y1aodyip1#

我总是在得到Jackson反序列化API后检查一些字段是否为空。但是我认为您可以扩展Jackson反序列化器来重写反序列化方法以达到您的目的。

xytpbqjk

xytpbqjk2#

检查它是否等于空对象:
@NoArgsConstructor
    @Getter
    @Setter
    @ToString
    @EqualsAndHashCode
    @JsonIgnoreProperties
    public class Foo {
        private String a;
        private String b;
        private String c;
        private String d;
    }

    public class FooMain {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private static final Foo EMPTY_FOO = new Foo();

    public static void main(String[] args) {
        try {
            // This attempt will throw an exception:        
            Optional.ofNullable(OBJECT_MAPPER.readValue("{}", Foo.class))
                    .filter(foo1 -> !foo1.equals(EMPTY_FOO))
                    .orElseThrow(IllegalArgumentException::new);
            // This attempt will not throw an exception:
            Optional.ofNullable(OBJECT_MAPPER.readValue("{a:\"123\"}", Foo.class))
                    .filter(foo1 -> !foo1.equals(EMPTY_FOO))
                    .orElseThrow(IllegalArgumentException::new);

        } catch (JsonProcessingException e) {
            // cannot deserialize json string to FOO  
        }
    }
}
6ie5vjzr

6ie5vjzr3#

如果需要一组字段中的 all

如果使用建构函式来还原序列化对象,您可以使用@JsonProperty注解中的required
例如,对于类Foo,字段name是必需的:

class Foo
{
    String name;
    Integer number; 

    @JsonCreator
    public Foo(
       @JsonProperty(value = "name", required = true) String name,
       @JsonProperty(value = "number") Integer number)
    {
        this.name = name;
        this.number = number;
    }
    // ... more methods ...
}

当尝试从没有name属性的JSON反序列化时,将失败,并返回MismatchedInputException

objectMapper.readValue("{}", Foo.class); // FAILURE

请注意,如果JSON对象显式地将字段设置为null,则会成功:

objectMapper.readValue("{\"name\": null}", Foo.class); // SUCCESS

如果一组字段中的 any 必须存在:

这是上一个例子的简单变体,因为我们可以将验证逻辑放在@JsonCreator注解的构造函数中。
例如:

class Foo
{
    String name;
    Integer number;

    @JsonCreator
    public Foo(
       @JsonProperty("name") String name,
       @JsonProperty("number") Integer number)
    {
       if (name == null && number == null)
            throw new IllegalArgumentException("at least one of (name, number) fields must be non-null");

       this.name = name;
       this.number = number;
    }
    // ... more methods ...    
}

相关问题