【发布时间】: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。