How to serialize nested objects limiting depth of serialization?

前端 未结 1 411
闹比i
闹比i 2020-12-21 16:54

There is a simple POJO - Category with Set as subcategories inside. Nesting might be quite deep as each of subcategories may contai

相关标签:
1条回答
  • 2020-12-21 17:47

    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.

    0 讨论(0)
提交回复
热议问题