net.sf.json.JSONException: There is a cycle in the hierarchy!的解決辦法

   使用Hibernate manytoone屬性關聯主表的時候,若是使用JSONArray把pojo對象轉換成json對象時,很容易出現循環的異常。解決的辦法就是,java

在轉換json對象時忽略manytoone屬性的對象。好比student類中有course屬性,忽略course屬性,就不會再出錯。web

    當pojo對象中存在時間(Date)類型時,轉換成json後的對象,時間格式不符合使用要求。在轉換時,能夠定義時間的格式。json

public String getJson(List<Student> list){
         JsonConfig jsonConfig = new JsonConfig();  //創建配置文件
         jsonConfig.setIgnoreDefaultExcludes(false);  //設置默認忽略
         jsonConfig.setExcludes(new String[]{"course"});         
        // 設置javabean中日期轉換時的格式
          jsonConfig.registerJsonValueProcessor(Date.class,
          new JsonDateValueProcessor("yyyy-MM-dd"));
        JSONArray json=JSONArray.fromObject(list,jsonConfig);
        return json;
}
                

時間格式轉換輔助類ide

package org.jeecgframework.web.ksxdcgzh.entity;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class JsonDateValueProcessor implements JsonValueProcessor{
     private String format = "yyyy-MM-dd HH:mm:ss";  
      
        public JsonDateValueProcessor()  
        {  
        }  
      
        public JsonDateValueProcessor(String format)  
        {  
            this.format = format;  
        }  
       
    @Override
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        // TODO Auto-generated method stub
         String[] obj = {};  
            if (value instanceof Date[])  
            {  
                SimpleDateFormat sf = new SimpleDateFormat(format);  
                Date[] dates = (Date[]) value;  
                obj = new String[dates.length];  
                for (int i = 0; i < dates.length; i++)  
                {  
                    obj[i] = sf.format(dates[i]);  
                }  
            }  
            return obj;  
    }

    @Override
    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
        // TODO Auto-generated method stub
        if (value instanceof Date)  
        {  
            String str = new SimpleDateFormat(format).format((Date) value);  
            return str;  
        }  
        return value;  
    }
     public String getFormat()  
        {  
            return format;  
        }  
      
        public void setFormat(String format)  
        {  
            this.format = format;  
        }  

}

 2 this

 在一對多的實體關係中,轉換json時要忽略引用的屬性。spa

@Entity
@Table(name = "studentl", schema = "")
@DynamicUpdate(true)
@DynamicInsert(true)
@SuppressWarnings("serial")
@JsonIgnoreProperties(value={"course"}) //轉換json時忽略course對象,以避免形成死循環
public class StudentEntity implements java.io.Serializable {
    private courseEntity course;
   ......
}
相關文章
相關標籤/搜索