for循环中的JSONArray.add(JSONObject)替换了for循环中的旧值,而Array由循环中的最后一个值组成

时间:2019-03-22 05:10:21

标签: java arrays json api

嗨,下面是一个简单的方法,我正在使用该方法根据其他API响应中的数组长度动态生成JSON请求。

但是在for循环中,一切似乎都可以正常工作,除非在最后调用JSONArray.add时,它将数组内部的旧jsonObject值替换为一个新的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 个答案:

答案 0 :(得分:0)

问题在于您的currentJsonColumnObject对象在for循环中分配。

您在引用currentJsonColumnObject的所有迭代中使用相同的对象currentJsonColumnArr.get(0)

要解决您的问题,您需要为currentJsonColumnObject设置另一个对象。

JSONArray jsonArray = JsonPath.parse(responseofotherapi).read("$.columns");
JSONArray dataSetColumnArray = new JSONArray();

JSONArray currentJsonColumnArr= JsonPath.parse(dataSetObj).read("$.columns");
//object will be set inside loop
JSONObject currentJsonColumnObject;

LinkedHashMap<String,Object> currentColumn;

for(int columnNumber = 0; columnNumber < jsonArray.size(); columnNumber++){

    currentColumn= (LinkedHashMap<String,Object>)jsonArray.get(columnNumber);

    // getting object from `currentJsonColumnArr` instead of using the same.
    currentJsonColumnObject= (JSONObject) currentJsonColumnArr.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();

}