解析JSON时遇org.json.JSONException问题求助:字段未找到、数组无对象
Hey there, let's break down and solve these JSON parsing headaches you're facing!
Issue 1: org.json.JSONException: "JSON object not found in JSON array"
This error usually pops up in two scenarios:
- You're trying to extract a
JSONObjectfrom an empty JSON array (like[]) - You're treating a JSON array as a single object, or accessing an index that doesn't exist in the array
Quick Fix:
First, validate the array structure before accessing its elements:
String rawJson = response.getBody().toString(); try { // Check if the response starts with an array bracket if (rawJson.trim().startsWith("[")) { JSONArray jsonArray = new JSONArray(rawJson); // Guard against empty arrays if (jsonArray.length() == 0) { System.out.println("Warning: Received empty JSON array"); return; } // Access the first object in the array (adjust index as needed) JSONObject targetObj = jsonArray.getJSONObject(0); // Proceed to parse targetObj's properties } else { // If it's a single object instead of an array JSONObject jsonObj = new JSONObject(rawJson); // Parse object properties } } catch (JSONException e) { e.printStackTrace(); }
Issue 2: org.json.JSONException: JSONObject["total"] not found & JSONObject["stars"] not found
These errors typically stem from one of three root causes:
- You're not getting the actual JSON content: Many HTTP clients (like OkHttp) return a debug string when you call
toString()on the response body, not the raw JSON. - The JSON structure isn't what you expect: The
totalandstarsfields might be nested inside a child object or array. - Typos in key names: Double-check if the keys are exactly
total/stars(case-sensitive!).
Step-by-Step Fix:
First, get the real JSON string:
If you're using OkHttp, replaceresponse.getBody().toString()withresponse.body().string()(note: this method can only be called once, since it consumes the input stream):// Correct way to get raw JSON from OkHttp response String realJson = response.body().string(); System.out.println("Raw JSON Response: " + realJson); // Print this to check structureInspect the printed JSON structure:
Suppose the actual JSON looks like this (nested fields):{ "meta": { "total": 42, "stars": 5 } }You can't directly access
totalfrom the top-level object—you need to drill into the nestedmetaobject first:JSONObject topLevelObj = new JSONObject(realJson); JSONObject metaObj = topLevelObj.getJSONObject("meta"); int total = metaObj.getInt("total"); int stars = metaObj.getInt("stars");Safe parsing with fallback values:
UseoptXXX()methods instead ofgetXXX()to avoid exceptions when fields are missing, and set sensible defaults:JSONObject jsonObj = new JSONObject(realJson); int total = jsonObj.optInt("total", 0); // Returns 0 if "total" is missing String stars = jsonObj.optString("stars", "No rating"); // Returns fallback string
Final Checklist:
- Always print the raw JSON response first to confirm its structure
- Verify you're correctly extracting the response body (avoid accidental
toString()calls on body objects) - Use
has()to check if a key exists before accessing it:if (jsonObj.has("total")) { ... } - Handle empty arrays/objects explicitly to prevent index or missing object errors
内容的提问来源于stack exchange,提问作者Dylan Czenski

