Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

java - How to serialize nested objects limiting depth of serialization?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...