首页 > 解决方案 > 如何让杰克逊在序列化时不将字段输出到 XML

问题描述

与这个问题类似,我想忽略我的 java 中的一个字段POJO。但是,我想始终忽略该字段,无论它是否为空。

在我的情况下,我需要为逻辑填充字段值,但稍后当我输出我的 xml 时,我不希望包含此字段。

@AllArgsConstructor
@NoArgsConstructor
public class MyNotification {
    @Setter @Getter private String id;
    @Setter @Getter private String time;
    @Setter @Getter private String flag;
    @Setter @Getter private String event;
    @Setter @Getter private String type;
}

输出应如下所示:

    <MyNotification>
        <id>112314</id>
        <time>2019-08-20T08:41:45Z</time>
        <flag>new</flag>
        <type>T01</type>
    </MyNotification>

已经尝试过,@JsonIgnore但在使用时该字段不会被填充。

标签: javaxmlserializationjacksondeserialization

解决方案


您应该使用JsonIgnoreProperties

@JsonIgnoreProperties(value = "event", allowSetters = true)
class MyNotification

来自文档allowSetters

可以启用以允许使用“setter”的属性(即,防止忽略 value() 中列出的属性的 setter)。


推荐阅读