简体   繁体   中英

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. 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.

Anyone know how to achieve this?

One way of achieving something similar is to use a 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:

@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. We only want to serialize 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:

// 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:

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

And the string will contain:

{"fullName":"Johnny Puma"}

By changing visibility settings. This question:

how to specify jackson to only use fields - preferably globally

seems to have settings you can use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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