简体   繁体   English

杰克逊反序列化缺少的默认值

[英]Jackson deserialize default values missing

I try to deserialize a JSON object that I receive in my API using the following code: 我尝试使用以下代码反序列化我在API中收到的JSON对象:

ObjectMapper mapper = new ObjectMapper();
ExampleDto ed = mapper.readValue(req.body(), ExampleDto.class);

My class uses Lombok to generate constructors, getters and setters, and looks like this: 我的类使用Lombok生成构造函数,getter和setter,看起来像这样:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExampleDto {
    private String name = "";
    private List<String> values = new LinkedList<>();
}

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 但是,如果我现在尝试反序列化JSON

{name: "Foo"}

the values field is null . values字段为null From my understanding, and all example code I found, values should be an empty list. 根据我的理解,以及我发现的所有示例代码, values应该是一个空列表。

Edit: Not a duplicate, as I'm using Lombok without Optionals 编辑:不重复,因为我使用没有Optionals的Lombok

@AllArgsConstructor creates the following constructor @AllArgsConstructor创建以下构造函数

@ConstructorProperties({"name", "values"})
ExampleDto(String name, List<String> values) {
    this.name = name;
    this.values = values;
}

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. 构造函数使用@ConstructorProperties进行批注,这意味着可以使用基于属性的创建者(参数构造函数或工厂方法)来实例化来自JSON对象的值,因此jackson-databind使用此构造函数从ExampleDto类实例化对象。

When the following line executes 当以下行执行时

mapper.readValue("{\"name\": \"Foo\"}", ExampleDto.class);

because there's no value for values in the provided JSON, null is passed for the second argument when the constructor is invoked. 因为提供的JSON中的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 如果删除@AllArgsConstructor注释,jackson-databind将使用setter方法初始化对象,在这种情况下, values不会为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM