Reputation: 720
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
Upvotes: 40
Views: 50303
Reputation: 10853
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"
}
Upvotes: 70
Reputation: 51
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
Upvotes: -5