杰克逊 - 不要序列化懒惰的对象 [英] jackson - do not serialize lazy objects

查看:144
本文介绍了杰克逊 - 不要序列化懒惰的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体:

@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;

}

然后我有一个控制器,其目的是检索书籍,我的问题是,类型字段被包含在我的控制器的json响应中。当jackson序列化对象时,我可以用任何方式排除那些延迟加载的字段吗?

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?

这是我的ObjectMapper的配置:

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);

谢谢!

我不能将它标记为JsonIgnore,因为它将永远不在序列化框中。有时候我需要随书检索这些类型,然后我将在查询中使用fetch join,因此它不会为空。

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.

推荐答案

您可以使用Jackson @JsonInclude 注释执行此操作。

You can do this with the Jackson @JsonInclude annotation.

根据最新版本的javadoc(2.4现在)如果字段值为null或为空,则可以使用简单注释指定是否包含带注释的属性。

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.

默认情况下,它是 JsonInclude.Include.ALWAYS ,这意味着即使您的懒惰未加载值为null,Jackson也会包含该属性。

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.

指定不包含空值或空值可以显着减小JSON响应的大小,包括所有好处..

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

如果要更改此行为,你c在类级别或单个属性/ getterMethod级别添加注释。

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

尝试将以下注释添加到您不希望包含的字段(如果为空): / p>

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;

这篇关于杰克逊 - 不要序列化懒惰的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆