小编典典

如何序列化嵌套对象限制序列化的深度?

json

有一个简单的POJO-
内部Category带有Set<Category>子类别。嵌套可能会很深,因为每个子类别都可能包含子子类别,依此类推。我想Category通过jersey
返回为REST资源,序列化为json(由jackson提出)。问题是,我不能真正限制序列化的深度,因此所有类别树都可以序列化。

有没有办法在完成第一级(即Category具有其第一级子类别)后立即停止对杰克逊进行序列化的对象?


阅读 305

收藏
2020-07-27

共1个答案

小编典典

如果可以从POJO中获取当前深度,则可以使用具有限制的ThreadLocal变量来实现。在控制器中,在返回Category实例之前,请对ThreadLocal整数设置深度限制。

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

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

您可能需要以某种方式清理本地线程,也许是使用spring的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序列化器。

2020-07-27