【问题标题】:How to serialize nested objects limiting depth of serialization?如何序列化嵌套对象限制序列化深度?
【发布时间】:2014-03-14 08:23:41
【问题描述】:

有一个简单的 POJO - Category,其中 Set<Category> 作为子类别。嵌套可能非常深,因为每个子类别都可能包含子子类别等等。 我想通过球衣将Category 作为 REST 资源返回,序列化为 json(由杰克逊)。问题是,我不能真正限制序列化的深度,因此所有类别树都会被序列化。

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

【问题讨论】:

  • 我对您使用的库不是很熟悉,但是,也许将子类别标记为瞬态?

标签: java json serialization jersey jackson


【解决方案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 序列化程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    相关资源
    最近更新 更多