Fastjson parsing json object appears $ref: "$.list[0]" solution

Today, a JSONObject object is defined, the referenced com.alibaba.fastjson.JSONObject, the cycle assigning value to this object appears "$ref": "$[0]" phenomenon,

/**
 * Duplicate reference of $ref object in fastjson
 * 
 * Introduction:
 * FastJson provides the SerializerFeature.DisableCircularReferenceDetect serialization option to turn off reference detection.
 * After turning off the reference check, it will not be replaced by $ref when the object is repeatedly referenced, but it will also cause a StackOverflowError exception when it is cyclically referenced.
 * 
 * Usage:
 * JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);
 */

The wrong way to write:

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

The above wording will cause circular references, because in a collection, when assigning values ​​to the same object circularly, it will be considered as an object, and $ref will appear .

It can be modified as follows:

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

 

 

 

Guess you like

Origin blog.csdn.net/Crystalqy/article/details/108084726