Android中如何将JSONObject内的对象批量转换为JSONArray
Iterate Through JSONObject and Auto-Populate JSONArray
Got it, dealing with 100+ manual getJSONObject() calls is definitely a pain—let's fix that with automatic iteration. Here's how you can loop through all keys in your charts object and add each chart to a JSONArray without manual work:
First, forget the index-based for loop you started with—JSONObject doesn't work that way. Instead, we'll use the keyset of the JSONObject to iterate through every unique key (like "system_voltage", "temperature1", etc.).
Step-by-Step Code Implementation
// Your existing line to get the charts JSONObject JSONObject chartss = objData.getJSONObject("charts"); // Initialize the JSONArray that will hold all chart objects JSONArray chartArray = new JSONArray(); // Get an iterator for all keys in the charts JSONObject Iterator<String> chartKeys = chartss.keys(); // Loop through each key while (chartKeys.hasNext()) { String currentKey = chartKeys.next(); // Fetch the chart object for the current key JSONObject singleChart = chartss.getJSONObject(currentKey); // Add this chart object to the JSONArray chartArray.put(singleChart); } // Now chartArray contains all your chart objects, ready to use!
How This Works
chartss.keys()returns an iterator over all top-level keys in yourchartsJSONObject—perfect for handling any number of entries, whether it's 3 or 300.- For each key, we fetch the corresponding chart object using
getJSONObject(currentKey)and add it directly to the JSONArray. - Since all keys in a JSONObject are unique (as you mentioned), you don't have to worry about duplicates or missing entries.
Optional: Keep Track of Keys (If Needed)
If you need to retain the original key (like "system_voltage") alongside the chart data, you can modify each chart object to include the key as a new field before adding it to the array:
while (chartKeys.hasNext()) { String currentKey = chartKeys.next(); JSONObject singleChart = chartss.getJSONObject(currentKey); // Add the key as a new property (e.g., "chart_id") singleChart.put("chart_id", currentKey); chartArray.put(singleChart); }
内容的提问来源于stack exchange,提问作者asus
相关产品推荐
相关产品推荐

