简体   繁体   中英

How to make Jackson ignore a get() method when serializing an object

I have this code in a class named Project :

@Transient
public List<Release> getAllReleases() {
    List<Release> releases = new ArrayList<Release>();
    ...
    return releases;
}

When a project object is serialized the getAllReleases() method is called, and an allReleases field is added to the serialized object.

If I add @JsonIgnore before the method I get the same result. So I wonder how can I implement a getFoo() method which is ignored by Jackson when serializing the object.

Alternatively I could do:

static public List<Release> getAllReleases(Project proj) {
    List<Release> releases = new ArrayList<Release>();
    ...
    return releases;
}

but the solution looks a bit ugly, and I'm pretty sure there must be some simpler mechanism provided by Jackson.

Am I missing something? TIA

If you mark the getter method with the @JsonIgnore annotation it should not be serialized. Here is an example:

public class JacksonIgnore {

    public static class Release {
        public final String version;

        public Release(String version) {
            this.version = version;
        }
    }
    public static class Project {
        public final String name;

        public Project(String name) {
            this.name = name;
        }

        @JsonIgnore
        public List<Release> getAllReleases() {
            return Arrays.asList(new Release("r1"), new Release("r2"));
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Project("test")));
    }
}

Output:

{
  "name" : "test"
}

You need to implement a JSon serializer which does nothing and then set it using @JSonSerialize(using = EmptySerializer.class).

Click on the refrence for further example.

Reference: Jackson: how to prevent field serialization

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