39

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

saste
  • 710
  • 2
  • 11
  • 19

2 Answers2

67

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"
}
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48
  • 5
    Struggling with dependencies, looks like my project is using both jackson1 (org.codehaus.jackson) and jackson2 (com.fasterxml.jackson), and they seem to conflict. The REST controller is apparently using jackson1 and ignoring the annotations used in the model. – saste May 06 '14 at 12:28
-5

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

Community
  • 1
  • 1
Excelsior
  • 51
  • 4