You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Java中如何获取JSONObject的所有键及子键?

How to Collect All Keys from Nested JSON Objects (Including Arrays)

Ah, right—JSONObject.names() or keySet() only grab the top-level keys, which doesn’t help when you have nested objects or arrays of objects like your data array. The solution here is to use a recursive traversal to dig through every level of the JSON structure and collect all keys along the way.

Here’s a step-by-step implementation using the org.json library (since you’re working with JSONObject):

Step 1: Create a Recursive Helper Method

This method will take any JSON element (object, array, or primitive) and a set to accumulate keys (using a Set ensures we get unique keys even if they appear in multiple nested objects).

import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashSet;
import java.util.Set;

private static void collectAllKeys(Object jsonElement, Set<String> keySet) {
    // Handle JSON objects: iterate through keys and recurse on their values
    if (jsonElement instanceof JSONObject) {
        JSONObject jsonObj = (JSONObject) jsonElement;
        for (String key : jsonObj.keySet()) {
            keySet.add(key);
            try {
                Object value = jsonObj.get(key);
                collectAllKeys(value, keySet);
            } catch (Exception e) {
                // Skip any invalid elements (adjust error handling based on your needs)
                e.printStackTrace();
            }
        }
    }
    // Handle JSON arrays: iterate through each element and recurse
    else if (jsonElement instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) jsonElement;
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                Object element = jsonArray.get(i);
                collectAllKeys(element, keySet);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    // Primitive values (strings, numbers, booleans, null) have no keys, so do nothing
}

Step 2: Use the Helper Method on Your Root JSONObject

Call the helper with your root object and a set to collect all keys:

public static void main(String[] args) {
    String yourJson = "{ \"per_page\": 3, \"total\": 12, \"data\": [{ \"color\": \"#98B2D1\", \"year\": 2000, \"name\": \"cerulean\", \"id\": 1, \"pantone_value\": \"15-4020\" }, { \"color\": \"#C74375\", \"year\": 2001, \"name\": \"fuchsia rose\", \"id\": 2, \"pantone_value\": \"17-2031\" } ], \"page\": 1, \"total_pages\": 4 }";
    
    JSONObject rootObj = new JSONObject(yourJson);
    Set<String> allKeys = new HashSet<>();
    
    collectAllKeys(rootObj, allKeys);
    
    // Print all collected keys
    System.out.println("All keys across all levels:");
    allKeys.forEach(System.out::println);
}

What This Does:

  • Starts at the root JSONObject and adds all top-level keys (per_page, total, data, page, total_pages) to the set.
  • When it hits the data array, it iterates over each object in the array.
  • For each object in the array, it adds its keys (color, year, name, id, pantone_value) to the set.
  • Since we’re using a HashSet, duplicate keys (like color appearing in both objects in the data array) are only stored once.

Notes:

  • If you want to keep duplicate keys (though this is unusual for JSON), replace HashSet with ArrayList and add every key you encounter (even duplicates).
  • The try-catch blocks handle cases where getting a value might throw a JSONException (e.g., invalid JSON structure). Adjust error handling based on your use case.
  • This approach works for any depth of nesting—whether you have objects inside objects inside arrays, etc.

When you run this code, you’ll get exactly the list of keys you need: per_page, total, data, color, year, name, id, pantone_value, page, total_pages.

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

火山引擎 最新活动