是否有可能使Jackson ObjectMapper反序列化失败,当没有属性映射导致一个空对象? &g



我正在努力解决一个问题:如果没有字段映射,是否可以配置杰克逊抛出错误?

示例:反序列化一个空对象("{}")或不包含目标对象包含的任何字段。

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

检查是否等于空对象:

@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  
}
}
}

ifallfrom as set of fields:

如果使用构造函数对对象进行反序列化,则可以从@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

如果任何从一组字段必须出现:

这是前一种情况的简单变化,因为我们可以将验证逻辑放在@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 ...    
}

最新更新