繁体   English   中英

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

[英]Jackson: how to include null value property in JSON serialization

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

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

@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)

我的响应实体:

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

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

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

我想得到以下回复:

{
    "data" : {
        "name" : "Name",
        "time" : null
    },
    "error" : null
}

JsonInclude添加到相关类ResponseData

(使用@ThomasFritsch 评论更新)

@JsonInclude(JsonInclude.Include.ALWAYS)

指示始终包括属性的值,与属性的值无关。

谢谢您的回答! 正如我所提到的,我仅限于 Jackson 1.9.13,并且我尝试了以下 Jackson 注释的多种组合,但没有成功:

@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)

然后我使用了以下内容:

@XmlElement(nillable = true)

错误和名称属性的注释并且它有效。 现在我得到了正确的 JSON 响应。

错误属性解决方法:

@XmlElement(nillable = true)
@JsonProperty("error")
private Error error;

暂无
暂无

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

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