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 there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
Ignore Fields Using Filters Finally, we can also use filters to ignore specific fields in Jackson. First, we need to define the filter on the Java object: @JsonFilter("myFilter") public class MyDtoWithFilter { ... }
Jackson default include null fields 1.2 By default, Jackson will include the null fields. To ignore the null fields, put @JsonInclude on class level or field level.
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" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With