Jackson is a helpful tool when building REST API’s. In this post I will explain what Jackson annotations I use all the time. There are of course many more Jackson annotations for all situations (example tutorials here). Here we focus on the things you want to have top of mind.

We will use the following data in all our examples. These are mapped to Json as the output of the examples.

name: Sybren
siblings: 3
pin: 8933
length: null
dateOfBirth: 5th July 1989

@JsonPropery

Arguably the most common Jackson annotation. This annotation is used to expose a property under a different name. Sometimes properties that keep their name are redundantly annotated with @JsonProperty.

public class Person {
    @JsonProperty("firstName")
    public String name;

    @JsonProperty("siblings")
    public int siblings;
}
{
    "firstName":"Sybren",
    "siblings":3
}

@JsonAutoDetect

The @JsonAutoDetect annotation in used to include non public properties when reading and writing objects. Other visibility matchers are DEFAULT, NON_PRIVATE, NONE and PROTECTED_AND_PRIVATE.

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class Person {
    private String name;
    private int siblings;
}
{
    "name":"Sybren",
    "siblings":3
}

@JsonIgnore

Used when a property should not be exposed in the output. With @JsonIgnoreProperties you can ignore multiple properties but this is not that common.

public class Person {
    public String name;

    @JsonIgnore
    public String pin;
}
{
    "name":"Sybren"
}

@JsonInclude

Deceivingly this annotation is used to exclude properties with null, empty or default values.

@JsonInclude(Include.NON_NULL)
public class Person {
    public String name;
    public int length;
}
{
    "name":"Sybren"
}

@JsonFormat

We can use the @JsonFormat annotation to map Json strings representing dates to Java Date objects. We have to specify the pattern in which we expect the date strings.

public class Person {
    public String name;

    @JsonFormat(
      shape = JsonFormat.Shape.STRING,
      pattern = "yyyy-MM-dd")
    public Date dateOfBirth;
}
{
    "name":"Sybren",
    "dateOfBirth":"1989-07-05"
}

@JsonUnwrapped

This annotation comes into play with nested objects you want to flatten. Let’s say as a siblings object we use the following.

public class Siblings {
    public int numberOfSisters;
    public int numberOfBrothers;
}

Now we don’t want a nested structure in the Json. We want the properties numberOfSisters and numberOfBrothers to be in the top Person object.

public class Person {
    public String name;

    @JsonUnwrapped
    public Siblings siblings;
}
{
    "name":"Sybren",
    "numberOfSisters":1,
    "numberOfBrothers":2
}

These are pretty much all the Jackson annotations I use. The rest I look up when the situation comes up. Happy mapping!