jackson - 不要序列化惰性对象 [英] jackson - do not serialize lazy objects

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

问题描述

我有一个实体:

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

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

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

如果你想改变这个行为,你可以在类级别或单个属性/getterMethod级别添加注解.

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;

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

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