简体   繁体   English

Jackson 2.0忽略了课堂上的所有属性

[英]Jackson 2.0 ignore all properties on a class

I need the opposite of @JsonIgnore , I need to tell Jackson to ignore all properties on an object except the the ones I annotate. 我需要与@JsonIgnore相反,我需要告诉Jackson忽略对象上的所有属性,除了我注释的对象。 I don't accidentally want someone adding a property and forget adding a @JsonIgnore and then I expose it where I don't want to. 我不小心想要有人添加属性并忘记添加@JsonIgnore然后我将它暴露在我不想要的地方。

Anyone know how to achieve this? 谁知道如何实现这一目标?

One way of achieving something similar is to use a SimpleBeanPropertyFilter . 实现类似功能的一种方法是使用SimpleBeanPropertyFilter Filters does not solve the problem by using on the fields you wish to include but it solves the problem with simply defining which fields to be serialized. 过滤器不能通过在您希望包含的字段上使用来解决问题,但它通过简单地定义要序列化的字段来解决问题。

If you assume the following POJO: 如果您假设以下POJO:

@JsonFilter("personFilter")
public class Person {
    private final String firstName;
    private final String lastName;

    public Person(final String firstName, final String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getFullName() {
        return getFirstName() + " " + getLastName();
    }

    public String getLastName() {
        return lastName;
    }
}

The POJO has two properties ( firstName and lastName ) that we DO NOT want to serialize. POJO有两个我们不想序列化的属性( firstNamelastName )。 We only want to serialize fullName ). 我们只想序列化fullName )。

As you may have noticed, the @JsonFilter annotation at the top of the class points to a named filter that can be created like this: 您可能已经注意到,类顶部的@JsonFilter注释指向可以像这样创建的命名过滤器:

// A filter that filter out all except for fullName
FilterProvider filters =
        new SimpleFilterProvider().addFilter(
                "personFilter",
                SimpleBeanPropertyFilter.filterOutAllExcept("fullName"));

In the end, the only thing you need to do is to create your ObjectMapper by using the following: 最后,您需要做的唯一事情是使用以下内容创建您的ObjectMapper

final ObjectMapper mapper = new ObjectMapper();
String json = mapper.writer(filters).writeValueAsString(new Person("Johnny", "Puma"));

And the string will contain: 该字符串将包含:

{"fullName":"Johnny Puma"} {“fullName”:“Johnny Puma”}

By changing visibility settings. 通过更改可见性设置。 This question: 这个问题:

how to specify jackson to only use fields - preferably globally 如何指定jackson只使用字段 - 最好是全局

seems to have settings you can use. 似乎有你可以使用的设置。

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

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