Jackson:如何在 JSON 序列化中包含 null 值属性

pbj*_*y10 6 java null response jackson

我正在尝试使用我自己的 Java 实体类和 Jackson 注释来生成 JSON 响应。null我的 JSON 响应中必须有两个键值,但如果我将它们设置为它们null,它们就会从 JSON 中消失。不幸的是,我只能使用 Jackson 版本 1.9.13。

我已经尝试将值设置为null,使用

@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)
Run Code Online (Sandbox Code Playgroud)

我的响应实体:

public class Response {

@JsonProperty("data")
private Data data;

@JsonProperty("error")
private Error error;

public Data getData() {
    return data;
}

public void setData(PgSoftAuthData data) {
    this.data = data;
}

public Error getError() {
    return error;
}

public void setError(PgSoftError error) {
    this.error = error;
}
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试生成这样的响应:

Data data = new Data();
data.setName("Name");
data.setTime(null); // This key dissappear from JSON

Response responseSuccess = Response();
responseSuccess.setData(data);
responseSuccess.setError(null); // Error object disappear from JSON
Run Code Online (Sandbox Code Playgroud)

我想得到以下回复:

{
    "data" : {
        "name" : "Name",
        "time" : null
    },
    "error" : null
}
Run Code Online (Sandbox Code Playgroud)

use*_*900 6

将JsonIninclude添加到相关类中ResponseData

(使用@ThomasFritsch 评论更新)

@JsonInclude(JsonInclude.Include.ALWAYS)
Run Code Online (Sandbox Code Playgroud)

指示始终包含财产的值,与财产的价值无关。