You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历多个JsonObject?特定结构JSON遍历仅获最后一项问题

Troubleshooting: Only Getting the Last Item When Traversing Multiple JsonObjects

Hey Joshua, I’ve run into this exact issue before—let’s break down why you’re only seeing the last item and fix it right away!

The Most Common Culprit: Overwriting a Single Variable

Chances are your code looks something like this, where you’re reusing the same JsonObject variable in each loop iteration, overwriting its content every time:

// ❌ Wrong approach: Overwriting the same object each loop
JsonObject singleResult = new JsonObject();
JsonArray jsonArray = yourOriginalJson.getAsJsonArray();

for (JsonElement element : jsonArray) {
    JsonObject currentObj = element.getAsJsonObject();
    // This replaces the existing "data" entry every time
    singleResult.add("data", currentObj.get("targetField"));
}

// singleResult will only hold the last iteration's data

The Fix: Collect Objects in a Collection or JsonArray

Instead of overwriting one object, you need to collect each traversed JsonObject into a list or a new JsonArray. Here are two straightforward solutions:

Solution 1: Store All Objects in a List<JsonObject>

This is great if you need to work with the objects in your Java code later:

// ✅ Correct approach: Collect into a List
List<JsonObject> allJsonObjects = new ArrayList<>();
JsonArray sourceArray = yourOriginalJson.getAsJsonArray();

for (JsonElement element : sourceArray) {
    // Always check if the element is a JsonObject to avoid errors
    if (element.isJsonObject()) {
        JsonObject obj = element.getAsJsonObject();
        allJsonObjects.add(obj); // Add each object to the list instead of overwriting
    }
}

// Now you can iterate through the list to access all items
for (JsonObject obj : allJsonObjects) {
    String desiredValue = obj.get("yourKey").getAsString();
    System.out.println("Item: " + desiredValue);
}

Solution 2: Build a New JsonArray for JSON Output

If you need to return or save the result as a JSON array, construct a new JsonArray and add each processed object to it:

// ✅ Correct approach: Build a result JsonArray
JsonArray resultArray = new JsonArray();
JsonArray sourceArray = yourOriginalJson.getAsJsonArray();

for (JsonElement element : sourceArray) {
    if (element.isJsonObject()) {
        JsonObject currentObj = element.getAsJsonObject();
        // Optional: Process the object (e.g., extract specific fields)
        JsonObject processedObj = new JsonObject();
        processedObj.addProperty("id", currentObj.get("id").getAsInt());
        processedObj.addProperty("name", currentObj.get("name").getAsString());
        
        resultArray.add(processedObj); // Append to the array, no overwriting
    }
}

// resultArray now contains all your items as valid JSON
System.out.println(resultArray.toString());

Key Takeaway

The root issue is that you were modifying a single JsonObject instance through each loop iteration—each pass replaced the previous data. By collecting each object into a list or array, you preserve every item you traverse.

Quick pro tip: Always add a check with element.isJsonObject() before casting to avoid ClassCastException if your JSON array has mixed element types!

内容的提问来源于stack exchange,提问作者Joshua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:29:24