【问题标题】:Jackson - way to define custom bean is empty for serialization杰克逊 - 定义自定义 bean 的方式对于序列化是空的
【发布时间】:2025-11-22 07:55:02
【问题描述】:

Jackson 序列化时定义自定义 bean 为空的正确方法是什么?

我想通过 Json->POJO->Json 过滤不需要的字段。我想如果自定义 bean 对象内的所有变量都为空,则在序列化为 JSON 时不会出现自定义 bean 对象。如果里面的任何变量不为null,则应该出现自定义bean对象。

目前,如果属于自定义 bean 的所有变量都为空,我有一个额外的方法可以为自定义 bean 分配空值。我正在寻找的是杰克逊是否可以做到这一点。

public class JsonFileContext {

    //...Some variables

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @JsonView(Views.In.class)
    private ContentRecognize contentRecognize;

    //...getter/setter method
}

ContentRecognize 类

public class ContentRecognize {

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String type;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private RecognizePattern targetId;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private RecognizePattern msgId;

    //...getter/setter method
}

预期输出

{
    "var1":"var1Content",
    "var2":"var2Content"
}

{
    "var1":"var1Content",
    "var2":"var2Content",
    "contentRecognize":{
        "type":"typeContent"
    }
}

电流输出

{
    "var1":"var1Content",
    "var2":"var2Content",
    "contentRecognize":{}
}

{
    "var1":"var1Content",
    "var2":"var2Content",
    "contentRecognize":{
        "type":"typeContent"
    }
}

【问题讨论】:

  • 能否添加ContentRecognize类的snip code?​​span>
  • 添加了ContentRecognize 类的@TanMaiVan 代码
  • 试试这个 - jsonschema2pojo.org 将 json 转换为 pojo 类
  • 本质上你想通过 Jackson 注释标记一个在序列化时被忽略的属性,对吧?
  • 或者查看*.com/questions/39005703/…,其中提到了password

标签: java json jackson


【解决方案1】:

您可以使用@JsonIgnoreProperties@JsonIgnore 注释之一。

@JsonIgnoreProperties

用于忽略序列化和反序列化中的某些属性,无论其值如何:

防止指定字段被序列化或反序列化(即不包含在 JSON 输出中;或者即使包含它们也被设置):@JsonIgnoreProperties({ "internalId", "secretKey" })

无一例外地忽略 JSON 输入中的任何未知属性:@JsonIgnoreProperties(ignoreUnknown=true)

@JsonIgnore

标记注解,表示被注解的方法或字段是 被基于自省的序列化和反序列化忽略 功能。也就是说,它不应该被认为是“getter”、“setter” 或“创造者”。

另外,从 Jackson 1.9 开始,如果这是唯一的注解 与一个属性相关联,它也会导致整个 要忽略的属性:也就是说,如果 setter 有这个注解并且 getter 没有注释,getter 也被有效地忽略了。它是 不同的访问者仍然可以使用不同的注解; 因此,如果只忽略“getter”,其他访问器(setter 或 字段)需要显式注释以防止忽略(通常 JsonProperty)。

在你的情况下,我会:

1:

@JsonIgnoreProperties({ "contentRecognize" })
public class JsonFileContext {
    [...]
}

2:

public class JsonFileContext {
    //...Some variables

    @JsonIgnore
    private ContentRecognize contentRecognize;

    //...getter/setter method
}

3:用@JsonIgnore注释contentRecognize getter

【讨论】:

    最近更新 更多