如何序列化嵌套对象限制序列化深度? [英] How to serialize nested objects limiting depth of serialization?

查看:615
本文介绍了如何序列化嵌套对象限制序列化深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的POJO - 类别,其中设置< Category> 作为子类别。嵌套可能非常深,因为每个子类别可能包含子子类别等等。
我想通过jersey返回 Category 作为REST资源,序列化为json(由jackson提供)。问题是,我无法真正限制序列化的深度,因此所有类别树都被序列化。

There is a simple POJO - Category with Set<Category> as subcategories inside. Nesting might be quite deep as each of subcategories may contain sub-subcategories and so on. I would like to return Category as REST resource via jersey, serialized to json (by jackson). The problem is, I can't really limit depth of serialization thus all the category tree gets serialized.

有没有办法在第一级完成后立即停止杰克逊序列化对象(即。类别及其第一级子类别?

Is there any way to stop jackson serializing object just right after first level is completed (ie. Category with its first-level subcategories)?

推荐答案

如果你可以从POJO获得当前深度,你可以使用一个ThreadLocal变量来保存限制。在控制器中,在返回Category实例之前,在ThreadLocal整数上设置深度限制。

If you can get current depth from a POJO you can do it with a ThreadLocal variable holding a limit. In a controller, before you return a Category instance set a depth limit on a ThreadLocal integer.

@RequestMapping("/categories")
@ResponseBody
public Category categories() {
    Category.limitSubCategoryDepth(2);
    return root;
}

在子类别getter中,您可以根据类别的当前深度检查深度限制,如果超过限制返回null。

In a subcategory getter you check depth limit against current depth of a category, if it's over the limit return null.

你需要以某种方式清理本地线程,可能使用spring的HandlerInteceptor :: afterCompletition。

You'll need to clean up thread local somehow, perhaps with a spring's HandlerInteceptor::afterCompletition.

private Category parent;
private Set<Category> subCategories;

public Set<Category> getSubCategories() {
    Set<Category> result;
    if (depthLimit.get() == null || getDepth() < depthLimit.get()) {
        result = subCategories;
    } else {
        result = null;
    }
    return result;
}

public int getDepth() {
    return parent != null? parent.getDepth() + 1 : 0;
}

private static ThreadLocal<Integer> depthLimit = new ThreadLocal<>();

public static void limitSubCategoryDepth(int max) {
    depthLimit.set(max);
}

public static void unlimitSubCategory() {
    depthLimit.remove();
}

如果你无法从POJO获得深度,你需要要么制作深度有限的树拷贝,要么学习如何编写自定义Jackson序列化器。

If you can't get depth from a POJO, you'll need to either make a tree copy with limited depth or learn how to code a custom Jackson serializer.

这篇关于如何序列化嵌套对象限制序列化深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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