如何遍历多个JsonObject?特定结构JSON遍历仅获最后一项问题
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

