Jackson Object Mapper

Last modified date

Comments: 0

@JsonInclude

@JsonInclude(JsonInclude.Include.NON_NULL)

The @JsonInclude(JsonInclude.Include.NON_NULL) instructs Jackson Object Mapper when serializing a pojo to ignore all fields that are null.

The JsonInclude.Include.NON_NULL literally means include everything in this pojo that doesn’t have a null value.

This is really useful for creating more generic model pojo objects that can adapt based on the data inside the pojo.

@JsonAnyGetter

The @JsonAnyGetter annotation is a method level annotation that can only be used on Map types.

It allows the contents of the Map object to be serialized as if the they were actual properties of the bean.

This is useful when serializing a pojo and you don’t want the root name of the map in the serialized json.

For example normally if we were to serialize this pojo:

public class User {
    @JsonProperty("user")
    String user;
    @JsonProperty("userData")
    Map<String, String> userData;
}

Jackson would serialize this into Json like this:

{
    "user": "Jaktech",
    "userData": {
        "attr1": "val1",
        "attr2": "val2"
    }
}

But if we want the Json to serialize without the root "userData" root attribute from the map like this:

{
    "user": "Jaktech",
    "attr1": "val1",
    "attr2": "val2"
}

Then we can use the @JsonAnyGetter property to extract the contents of the map and serialize the contents into the Json as if they were members of the pojo:

public class User {
    @JsonProperty("user")
    String user;

    Map<String, String> userData;

    @JsonAnyGetter
    public Map<String, String> getUserData() {
        return this.userData;
    }
    
}

This is a really useful way of being able to serialize a map in a pojo without the field name of the map being in the resulting Json.

References

https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonAnyGetter.html

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.