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

解析JSON时遇org.json.JSONException问题求助:字段未找到、数组无对象

Fixing Common org.json.JSONException Issues When Parsing Response Bodies

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 JSONObject from 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:

  1. 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.
  2. The JSON structure isn't what you expect: The total and stars fields might be nested inside a child object or array.
  3. Typos in key names: Double-check if the keys are exactly total/stars (case-sensitive!).

Step-by-Step Fix:

  1. First, get the real JSON string:
    If you're using OkHttp, replace response.getBody().toString() with response.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 structure
    
  2. Inspect the printed JSON structure:
    Suppose the actual JSON looks like this (nested fields):

    {
      "meta": {
        "total": 42,
        "stars": 5
      }
    }
    

    You can't directly access total from the top-level object—you need to drill into the nested meta object first:

    JSONObject topLevelObj = new JSONObject(realJson);
    JSONObject metaObj = topLevelObj.getJSONObject("meta");
    
    int total = metaObj.getInt("total");
    int stars = metaObj.getInt("stars");
    
  3. Safe parsing with fallback values:
    Use optXXX() methods instead of getXXX() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:27:02