Jackson 忽略外部库中超类的所有属性您可以使用混音或@JsonIgnoreProperties 使用混音

2022-09-02 21:49:41

我正在使用ORM进行开发,在其中扩展基orm类以创建表。

例如:

public class Person extends DbItem {
    @JsonIgnore
    private String index;

    private String firstName;

    private String lastName;
}

问题是,当我使用 ObjectMapper 进行序列化时,它会尝试序列化 DbItem 类的成员。有什么简单的方法来防止这种情况吗?例如,使用批注。

我看了一个类似的问题Jackson序列化:如何忽略超类属性,但我希望它可以做得更简单,我不确定我是否可以做到这一点,因为我无法更改超类,因为它在外部库中。


答案 1

您可以使用混音@JsonIgnoreProperties

出于这些示例的目的,假定基本 ORM 类和扩展为:

public class DbItem {
    public String dbPropertyA;
    public String dbPropertyB;
}

public class Person extends DbItem {
    public String index;
    public String firstName;
    public String lastName;
}

分别。

使用混音

混音是 Jackson 从对象本身理解的去序列化指令的抽象。这是一种自定义第三方类的反序列化的方法。为了定义 Mix-in,必须创建一个抽象类并将其注册到 .ObjectMapper

示例混入定义

public abstract class PersonMixIn {
    @JsonIgnore public String dbPropertyA;
    @JsonIgnore public String dbPropertyB;
    @JsonIgnore public String index;
}

注册混音

@Test
public void serializePersonWithMixIn() throws JsonProcessingException {
    // set up test data including parent properties
    Person person = makeFakePerson();

    // register the mix in
    ObjectMapper om = new ObjectMapper()
            .addMixIn(Person.class, PersonMixIn.class);

    // translate object to JSON string using Jackson
    String json = om.writeValueAsString(person);

    assertFalse(json.contains("dbPropertyA"));
    assertFalse(json.contains("dbPropertyB"));
    assertFalse(json.contains("index"));
    System.out.println(json);
}

@JsonIgnoreProperties

如果要避免创建类并配置 ,则可以使用注释。只需对要序列化的类进行批注,并列出要排除的属性。ObjectMapper@JsonIgnoreProperties

示例 可序列化对象

@JsonIgnoreProperties({"index", "dbPropertyA", "dbPropertyB"})
public class Person extends DbItem {
    public String index;
    public String firstName;
    public String lastName;
}

查看实际应用

@Test
public void serializePersonWithIgnorePropertiesAnnotation() throws JsonProcessingException {
    // set up test data including parent properties
    Person person = makeFakePerson();

    ObjectMapper om = new ObjectMapper();

    // translate object to JSON string using Jackson
    String json = om.writeValueAsString(person);

    assertFalse(json.contains("dbPropertyA"));
    assertFalse(json.contains("dbPropertyB"));
    assertFalse(json.contains("index"));
    System.out.println(json);
}

答案 2

您想要执行自定义字段级别序列化。这将需要更多的工作来维护您的代码库,但这是迄今为止最简单的解决方案。有关实现详细信息,请参阅某些字段的 Jackson JSON 自定义序列化