jackson - do not serialize lazy objects

villager picture villager · Sep 18, 2014 · Viewed 27k times · Source

I have an entity:

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column
    private String title;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = ("movie"),cascade = CascadeType.ALL)
    private List<Genre> genre;

}

Then I have a controller whose purpose is to retrieve books, my problem is that, the genre field is being included in the json response of my controller. Any way I can exclude those fields that are lazy loaded when jackson serializes the object?

This is the configuration of my ObjectMapper:

Hibernate4Module hm = new Hibernate4Module();
hm.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, false);
registerModule(hm);
configure(SerializationFeature.INDENT_OUTPUT, true);

Thanks!

I can't mark it as JsonIgnore, as it will be forever out of the serialization box. There will be times where I will need to retrieve the genres along with the book, and by then I will use "fetch join" on my query so it will not be null.

Answer

Davide Rossi picture Davide Rossi · Sep 29, 2014

You can do this with the Jackson @JsonInclude annotation.

According to the latest version's javadoc (2.4 right now) you can specify with a simple annotation if to include or not the annotated property if the field value is null or empty.

By default, it's JsonInclude.Include.ALWAYS, and this means that even if your lazily not-loaded values are null, Jackson does include the property.

Specifying to don't include empty or null values can significantly reduce the size of the JSON response, with all the benefits included..

If you want to change this behavior, you can add the annotation at class-level or single property/getterMethod level.

Try to add the following annotations to the fields you don't want to include if empty:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
@OneToMany(fetch = FetchType.LAZY, mappedBy = ("movie"),cascade = CascadeType.ALL)
private List<Genre> genre;