问题描述
我尝试使用以下代码反序列化我在API中收到的JSON对象:
I try to deserialize a JSON object that I receive in my API using the following code:
ObjectMapper mapper = new ObjectMapper();
ExampleDto ed = mapper.readValue(req.body(), ExampleDto.class);
我的类使用Lombok生成构造函数,getter和setter,如下所示:
My class uses Lombok to generate constructors, getters and setters, and looks like this:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExampleDto {
private String name = "";
private List<String> values = new LinkedList<>();
}
两个属性都应该是可选的,并使用类定义中指定的默认值如果他们没有提供。但是,如果我现在尝试反序列化JSON
Both properties should be optional, and use the default value specified in the class definition if they are not provided. However, if I now try to deserialize the JSON
{name: "Foo"}
值
字段是 null
。根据我的理解,以及我发现的所有示例代码, values
应该是一个空列表。
the values
field is null
. From my understanding, and all example code I found, values
should be an empty list.
编辑:不重复,因为我使用没有Optionals的Lombok
Not a duplicate, as I'm using Lombok without Optionals
推荐答案
@AllArgsConstructor
创建以下构造函数
@ConstructorProperties({"name", "values"})
ExampleDto(String name, List<String> values) {
this.name = name;
this.values = values;
}
构造函数用 @ConstructorProperties $注释c $ c>这意味着可以使用基于属性的创建者(参数构造函数或工厂方法)来实例化来自JSON对象的值,因此jackson-databind使用此构造函数从
ExampleDto $实例化对象c $ c> class。
The constructor is annotated with @ConstructorProperties
which means a property-based creator (argument-taking constructor or factory method) is available to instantiate values from JSON object so jackson-databind uses this constructor to instantiate an object from ExampleDto
class.
执行以下行时
mapper.readValue("{\"name\": \"Foo\"}", ExampleDto.class);
因为值
中没有值提供JSON时,在调用构造函数时为第二个参数传递 null
。
because there's no value for values
in the provided JSON, null
is passed for the second argument when the constructor is invoked.
如果删除 @AllArgsConstructor
注释jackson-databind将使用setter方法初始化对象,在这种情况下 values
将不是 null
If you remove @AllArgsConstructor
annotation jackson-databind would use setter methods to initialize the object and in this case values
would not be null
这篇关于杰克逊反序列化缺少的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!