今天定义了一个JSONObject对象,引用的com.alibaba.fastjson.JSONObject,循环给这个对象赋值出现"$ref":"$[0]"现象,
/** * fastjson中$ref对象重复引用问题 * * 介绍: * FastJson提供了SerializerFeature.DisableCircularReferenceDetect这个序列化选项,用来关闭引用检测。 * 关闭引用检测后,重复引用对象时就不会被$ref代替,但是在循环引用时也会导致StackOverflowError异常。 * * 用法: * JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect); */
错误的写法为:
List<CxmBdRole> roleList = new ArrayList<>();
CxmBdRole cxmBdRole = null;
for (Integer roleId : roleIdList) {
if (roleMap.containsKey(roleId)) {
cxmBdRole = roleMap.get(roleId).get(0);
cxmBdRole.setId(roletmp.getId());
cxmBdRole.setName(roletmp.getName());
cxmBdRole.setRemark(roletmp.getRemark());
roleList.add(cxmBdRole);
}
}
employ.setRoles(roleList);
上面的写法就会出现循环引用,因为一个集合中,给相同的对象循环赋值时,它会认为是一个对象,就出现$ref,
修改为下面的写法即可:
List<CxmBdRole> roleList = new ArrayList<>();
CxmBdRole cxmBdRole = null;
for (Integer roleId : roleIdList) {
if (roleMap.containsKey(roleId)) {
cxmBdRole = new CxmBdRole();// 每次都重新创建一个新的对象
CxmBdRole roletmp = roleMap.get(roleId).get(0);
cxmBdRole.setId(roletmp.getId());
cxmBdRole.setName(roletmp.getName());
cxmBdRole.setRemark(roletmp.getRemark());
roleList.add(cxmBdRole);
}
}
employ.setRoles(roleList);