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

Java提取JSON数组中动态键值对的实现疑问

Handling Dynamic Key-Value Pairs in JSON Arrays with Java

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

  1. keySet(): This method returns all the keys in the JSONObject as a Set<String>. Since your JSON objects only have one key each, this set will have exactly one element.
  2. iterator().next(): We use an iterator to grab that single key from the set.
  3. Parse the Key: Since your keys are numeric strings (like "1000"), we convert them to int with Integer.parseInt().
  4. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:24:02