net.sf.json.JSONException: There is a cycle in the

前端之家收集整理的这篇文章主要介绍了net.sf.json.JSONException: There is a cycle in the前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

因为项目中使用了Extjs技术,JAR包为:json-lib.jar, 在开发过程中遇到了一个JSON-LIB和Hibernate有关的问题:

net.sf.json.JSONException: There is a cycle in the hierarchy!
at net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:97)
at net.sf.json.JSONObject._fromBean(JSONObject.java:857)
at net.sf.json.JSONObject.fromObject(JSONObject.java:192)
at net.sf.json.JSONObject._processValue(JSONObject.java:2774)
at net.sf.json.JSONObject._setInternal(JSONObject.java:2798)
at net.sf.json.JSONObject.setValue(JSONObject.java:1507)
at net.sf.json.JSONObject._fromBean(JSONObject.java:940)
at net.sf.json.JSONObject.fromObject(JSONObject.java:192)
at net.sf.json.JSONObject._processValue(JSONObject.java:2774)
at net.sf.json.JSONObject._setInternal(JSONObject.java:2798)
at net.sf.json.JSONObject.setValue(JSONObject.java:1507)
at net.sf.json.JSONObject._fromBean(JSONObject.java:940)
at net.sf.json.JSONObject.fromObject(JSONObject.java:192)
at net.sf.json.JSONObject._processValue(JSONObject.java:2774)
at net.sf.json.JSONObject._setInternal(JSONObject.java:2798)
at net.sf.json.JSONObject.setValue(JSONObject.java:1507)
at net.sf.json.JSONObject._fromBean(JSONObject.java:940)
at net.sf.json.JSONObject.fromObject(JSONObject.java:192)
at net.sf.json.JSONObject._processValue(JSONObject.java:2774)
at net.sf.json.JSONObject._setInternal(JSONObject.java:2798)
at net.sf.json.JSONObject.setValue(JSONObject.java:1507)
at net.sf.json.JSONObject._fromBean(JSONObject.java:940)
at net.sf.json.JSONObject.fromObject(JSONObject.java:192)
at net.yanhl.IoUser.action.IoUserAction.loadUser(IoUserAction.java:142)

因为Hibernate中设置了自身关联:

//设置自身关联的组对象

public classUser implements Serializable {

private static final long serialVersionUID = 6202253180943473205L;
@ManyToMany(targetEntity = Role.class,fetch = FetchType.EAGER)
@JoinTable(name = "user_role",joinColumns = @JoinColumn(name = "user_id"),inverseJoinColumns = @JoinColumn(name = "role_id"))
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private Set<Role> roles;

@Transient
private Map<String,List<Resource>> roleResources;

起初想通过hibernate来解决问题,就是想过滤掉自身关联后来查资料发现不可能实现,最后找到通过JSON-LIB来过滤关联的集合属性代码如下:

JsonConfig config = new JsonConfig();
config.setJsonPropertyFilter(new PropertyFilter(){
public boolean apply(Object source,String name,Object value) {
if(name.equals("roles") || name.equals("roleResources")) {
return true;
} else {
return false;
}
}

});
List<User> list = (List<User>)userManagerImpl.findPaginatedList(user,perpage,current);
JSONArray arr = JSONArray.fromObject(list,config);

当JSON-LIB解析JAVABEAN时过滤掉roles、roleResources这两个属性,重新启动服务,pass

猜你在找的Json相关文章