java JSONArray。for循环中的add(JSONObject)正在替换for循环中的旧值,数组由循环中的最后一个值组成
下面是一个简单的方法,我使用它根据其他API响应的数组长度动态生成JSON请求
然而,在for循环中,除了在JSONArray结束时,一切似乎都正常工作。调用add时,它会将数组中的旧jsonObject值替换为新值,最后整个数组只包含相同的JSON对象集。 经过大量调试后找不到解决方案,是由于变量声明之类的。下面是我正在使用的方法
参考:我正在使用minidev。JSON
public JSONObject method1(JSONObject sampleJsonObjTemplate, String responseofotherapi) {
JSONArray jsonArray = JsonPath.parse(responseofotherapi).read("$.columns");
JSONArray dataSetColumnArray = new JSONArray();
JSONArray currentJsonColumnArr= JsonPath.parse(dataSetObj).read("$.columns");
JSONObject currentJsonColumnObject= (JSONObject) currentJsonColumnArr.get(0);
LinkedHashMap<String,Object> currentColumn;
for(int columnNumber = 0; columnNumber < jsonArray.size(); columnNumber++){
currentColumn= (LinkedHashMap<String,Object>)jsonArray.get(columnNumber);
String name = currentColumn.get("name").toString();
currentJsonColumnObject.put("name",name);
currentJsonColumnObject.put("alias",name+" Column Alias ");
currentJsonColumnObject.put("description",name+" Column Description ");
dataSetColumnArray.add(columnNumber,currentJsonColumnObject);
currentColumn.clear();
}
JSONObject updatedDataSetReq=JsonPath.parse(dataSetObj).set("$.columns",dataSetColumnArray).json();
return updatedDataSetReq;
}
# 1 楼答案
问题在于
currentJsonColumnObject
对象在for
循环中赋值对于所有引用
currentJsonColumnArr.get(0)
的迭代,您都使用相同的对象currentJsonColumnObject
要解决您的问题,您需要为
currentJsonColumnObject
设置一个不同的对象