“$.result.currentLevel”
问题描述
使用SpringMvc返回一个json数据的时候,会在产生的结果中出现如下的问题:”$.result.currentLevel”
{
"code": 200,
"msg": "请求成功",
"result": {
"currentLevel": {
"code": "20180417543114",
"createDate": 1526528076000,
"growup": 600,
"icon": "http://192.168.1.128:8080/pic/level-3.png",
"id": "31feff3a04c84ade99287f862bcfaa9b",
"isSys": "0",
"levelName": "王者会员",
"levelNum": 4,
"rebate": 5,
"setid": "c7a29d3f58ea4c6588a471f02fb32cd4",
"sort": 2
},
"maxLevel": {
"$ref": "$.result.currentLevel"
},
}
}
问题原因
由于被转换为json的对象存在引用
java代码:
MembersysLevel entity = new MembersysLevel();
entity.setCode();
List<MembersysLevel> membersysLevelList = membersysSetService.getLevels(entity);
MembersysLevel currentLevel = new MembersysLevel();
int currentLevelIndex = 0;
for (int i = 0, size = membersysLevelList.size(); i < size; i++) {
MembersysLevel membersysLevel = membersysLevelList.get(i);
if (resultBqUsers.getLevelId().equals(membersysLevel.getId())) {
//
currentLevel = membersysLevel;
currentLevelIndex = i;
break;
}
}
int maxLevelIndex = membersysLevelList.size() - 1;
MembersysLevel maxLevel = membersysLevelList.get(maxLevelIndex);
//上一个
MembersysLevel preMembersysLevel = new MembersysLevel();
//
if (currentLevelIndex + 1 < membersysLevelList.size()) {
preMembersysLevel = membersysLevelList.get(currentLevelIndex + 1);
}
return ResultBean.success()
.setResult("currentLevel", currentLevel)
.setResult("maxLevel", maxLevel)
.setResult("preMembersysLevel", preMembersysLevel)
.setResult("bqUsers", resultBqUsers);
解决的办法
将被引用的对象复制到一个新的地址,然后再去转换为json。即可
在上述代码中,会出现 maxLevel == currentLevel 这种现象,所以在最后就会出现json串的错误现象。我们可以通过java对象克隆的方式来进行解决。
MembersysLevel cloneMaxLevel = null;
if (maxLevel == currentLevel) {
//如果相等 那么clone
cloneMaxLevel = (MembersysLevel) currentLevel.clone();
}
水平有限,个人见解,如有错误,欢迎指正。博主QQ:337081267