我列出了要通过存储库和服务获取的对象。在尝试通过响应时,我尝试遍历每个对象。

JSONArray response = new JSONArray();

List < Object[] > ratings = new ArrayList < > ();

ratings = ratingService.getListOfSeller("active");

List < Object[] > objects = ratings;

if (objects.size() > 0) {

    for (Object object: objects) {
        JSONObject response2 = new JSONObject();
        response2.put("sellerID", objects.get(0)[1]);
        response.put(response2);
    }

} else {
    response = new JSONArray();
}


该代码段为我提供了相同的迭代次数结果。我如何遍历object.get(0)[1]中的每个对象

也尝试过这个,但是给出了一个错误。

if (objects.size() > 0) {
    for (int i = 0; i < objects.size(); i++) {
        JSONObject response2 = new JSONObject();
        response2.put("sellerID", objects.get(i)[i]);
        response.put(response2);
    }
} else {
    response = new JSONArray();
}



  错误java.lang.ArrayIndexOutOfBoundsException: 2

最佳答案

试试下面的代码

List<Object[]> ratings = new ArrayList<>();
JSONObject response2 = null;

for (Object[] objects : ratings) { //will loop through ratings List
    for (int i = 0; i < objects.length; i++) { //will loop through object array
        response2 = new JSONObject();
        response2.put("sellerID", objects[i]);
        response.put(response2);
    }
}

07-24 15:26