jackson - do not serialize lazy objects

后端 未结 4 1095
孤城傲影
孤城傲影 2020-12-03 05:55

I have an entity:

@Entity
public class Book {

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

    @Column
    private Stri         


        
4条回答
  •  温柔的废话
    2020-12-03 06:26

    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;
    

提交回复
热议问题