Reputation: 677
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)?
Upvotes: 2
Views: 5282
Reputation: 181
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.
Upvotes: 3