天天看點

JSON 轉換異常 死循環 There is a cycle in the hierarchy

There is a cycle in the hierarchy!

在使用Json轉換的時候報的一個錯誤。總結了一下錯誤的原因和解決的方法,分享給大家,有需要的可以看一下

産生的原因如下:

JSON 轉換異常 死循環 There is a cycle in the hierarchy
JSON 轉換異常 死循環 There is a cycle in the hierarchy

解決方式如下:

1.第一種情況比較簡單。既然我們知道上述死循環的原因是因為subareas字段跟region死循環了,那麼我們在轉化的時候去掉subareas,不轉化該字段就可以

//核心代碼
//對轉化json時進行配置
JsonConfig jsonConfig = new JsonConfig();
        //指定哪些屬性不需要轉化成json,這裡把subareas排掉就可以了
        jsonConfig.setExcludes(new String[]{"detachedCriteria","currentPage"});
           
public void java2Json() {
        //調用service層查詢資料庫
        regionService.pageQuery(pageBean);
        JsonConfig jsonConfig = new JsonConfig();
        //指定哪些屬性不需要轉化成json,這裡把subareas排掉就可以了
        jsonConfig.setExcludes(new String[]{"detachedCriteria","currentPage"});
        String jsonObject = JSONObject.fromObject(pageBean,jsonConfig).toString();
    ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
        try {
    ServletActionContext.getResponse().getWriter().println(jsonObject);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
//然後就沒問題了額
           
JSON 轉換異常 死循環 There is a cycle in the hierarchy

第一種情況,也可以采用以下的代碼

<!--使用setCycleDetectionStrategy防止自包含-->
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
           
//核心代碼
//對轉化json時進行配置
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
String jsonObject = JSONObject.fromObject(o,jsonConfig).toString();
           
JSON 轉換異常 死循環 There is a cycle in the hierarchy

【總結】:實際上該方法跟我們上述寫的是一樣的。它自動幫我們剔除了導緻循環的項 “subareas”

2.第二種情況,前端頁面展示的資料需要使用到subareas字段,也就是我們不能夠去掉它,去掉了在前端頁面就不能完整展示資料了。這種情況可以這麼辦

【分析過程如下:】其實,出現這種情況可以說是hibernate在轉json的時候延遲加載導緻的,如果說一開始我們把所有的資料從資料庫裡面查找出來,封裝到對象裡面,然後轉json的話就不會出現問題。問題現在是在轉化json的時候,遇到一個關聯對像的時候,它又從資料庫裡面去查找該字段,才會導緻說:死循環

JSON 轉換異常 死循環 There is a cycle in the hierarchy

【解決方法:】不要延遲加載,直接加載全部對象就可以了

JSON 轉換異常 死循環 There is a cycle in the hierarchy

【示範案例如下:】這裡有點難示範,簡單截取重要代碼

區域表和分區表是一對多的關系,在對象的世界裡面互相關聯

JSON 轉換異常 死循環 There is a cycle in the hierarchy
JSON 轉換異常 死循環 There is a cycle in the hierarchy
JSON 轉換異常 死循環 There is a cycle in the hierarchy
JSON 轉換異常 死循環 There is a cycle in the hierarchy