2014-02-14 3 views
2

내부에 하위 카테고리로 간단한 POJO - CategorySet<Category>이 있습니다. 중첩은 하위 범주 각각에 하위 하위 범주가 포함될 수 있으므로 매우 심층적 일 수 있습니다. Category을 저지를 통해 REST 리소스로 반환하고 json (jackson이)에게 serialize합니다. 문제는 직렬화의 깊이를 제한 할 수 없기 때문에 모든 범주 트리가 직렬화됩니다.직렬화 깊이를 제한하는 중첩 된 객체를 직렬화하는 방법은 무엇입니까?

첫 번째 수준이 완료된 직후에 잭슨 직렬화 개체를 중지 할 수있는 방법이 있습니까 (즉, 첫 번째 수준 하위 범주가있는 Category)?

+0

사용중인 라이브러리에 익숙하지 않지만 하위 카테고리를 임시로 표시 할 수 있습니까? –

답변

3

POJO에서 현재 깊이를 얻을 수 있다면 한계를 지닌 ThreadLocal 변수를 사용하여 수행 할 수 있습니다. 컨트롤러에서, Category 인스턴스를 반환하기 전에 ThreadLocal 정수에 깊이 제한을 설정하십시오.

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

제한 범주를 초과하는 경우 범주의 현재 깊이에 대한 깊이 제한을 검사합니다.

스프링의 HandlerInteceptor :: afterCompletition을 사용하면 어떻게 든 로컬 스레드를 정리해야합니다. 당신은 POJO에서 깊이를 얻을 수없는 경우

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

, 당신은 제한 깊이와 나무 복사본을 만들거나 사용자 정의 잭슨 serializer를 코딩하는 방법을 배울 중 하나를해야합니다.

관련 문제