简体   繁体   English

在响应中忽略 POJO 的空字段

[英]Ignore null field of a POJO in response

I have a class with few fields我有一个领域很少的课程

static final class Sample {
     Enum A, B, C, D;
     Sample(A, B, C) {
        // A,B,C init; not D (it's null)
     }
}

When I create an instance of Sample using 3 parameter constructor, I want to ignore 4th one while sending as response to an API call.当我使用 3 参数构造函数创建 Sample 实例时,我想在发送作为对 API 调用的响应时忽略第 4 个实例。

How can I achieve this?我怎样才能做到这一点? I can't use JsonIgnore because in other flow, D will have some non null values;我不能使用 JsonIgnore 因为在其他流程中, D 会有一些非空值;

您可以通过使用 @JsonInclude(Include.NON_NULL) 在类级别忽略空字段以仅包含非空字段,从而排除任何值为空的属性。

You have to add @JsonInclude(JsonInclude.Include.NON_NULL) of (com.fasterxml.jackson.annotation.JsonInclude;) on class level as below:您必须在类级别添加 (com.fasterxml.jackson.annotation.JsonInclude;) 的 @JsonInclude(JsonInclude.Include.NON_NULL),如下所示:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
class Sample {
     Enum A, B, C, D;
     Sample(A, B, C) {
        // A,B,C init; not D (it's null)
     }
}

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

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