Java提取JSON数组中动态键值对的实现疑问
Hey there! I totally get why this is tripping you up—working with dynamic keys (instead of fixed, known keys) in JSON is a common hurdle for Java beginners. Your original code is on the right track, but the issue is that JSONObject doesn't have getKey() or getValue() methods. Let's fix this step by step.
The Problem with Your Original Code
Your JSON data array contains objects where each has a unique, dynamic key (like "1000" or "100031") instead of a consistent key name (like "id"). So we can't just call a method to fetch the key directly—we need to retrieve the set of keys from each JSONObject first.
Solution Code
Assuming you're using the standard org.json library (the most common one for basic JSON handling in Java), here's how to adjust your loop:
JSONArray lastdtArr = json.getJSONArray("data"); int len = lastdtArr.length(); for(int i = 0; i < len; i++) { JSONObject lastdtid = lastdtArr.getJSONObject(i); // Get all keys from the current JSONObject (each has only one key in your case) Set<String> keySet = lastdtid.keySet(); // Add a check to avoid empty object errors if (!keySet.isEmpty()) { // Get the single key (since each object has exactly one key-value pair) String idStr = keySet.iterator().next(); try { // Convert the key string to an integer (matches your JSON key format) int id = Integer.parseInt(idStr); // Fetch the date value using the dynamic key String date = lastdtid.getString(idStr); // Now you can perform your operations with id and date System.out.printf("Processing ID: %d, Date: %s%n", id, date); } catch (NumberFormatException e) { // Handle cases where the key isn't a valid integer System.err.println("Skipping invalid ID format at index " + i + ": " + idStr); } } else { System.err.println("Empty JSON object found at index " + i); } }
How This Works
keySet(): This method returns all the keys in the JSONObject as aSet<String>. Since your JSON objects only have one key each, this set will have exactly one element.iterator().next(): We use an iterator to grab that single key from the set.- Parse the Key: Since your keys are numeric strings (like "1000"), we convert them to
intwithInteger.parseInt(). - Fetch the Value: Use the dynamic key to get the corresponding date string with
getString(idStr).
Bonus: Handling Edge Cases
I added basic error handling to cover:
- Empty JSONObject entries in the array
- Keys that aren't valid integers (in case your JSON ever has non-numeric keys)
This makes your code more robust and less likely to crash unexpectedly.
内容的提问来源于stack exchange,提问作者Tanu Gupta

