解析JSON触发JSONException,求排查及获取指定包测试列表方案
Oh, I see exactly what's going wrong here! The error message gives it away—you're trying to convert the string "screen_package" (which is just a key name) into a JSONObject, but that string isn't valid JSON itself.
Let me break down the mistake: When you iterate through jsonRootObject.keys(), currentPackageKey is the name of the key (like "camera_package" or "screen_package"), not the actual JSON object that key points to. So line 150 where you do new JSONObject(currentPackageKey) is trying to parse the string "screen_package" as JSON, which obviously fails because that's just a plain string, not a structured JSON object.
The Fix
Instead of creating a new JSONObject from the key string, you need to retrieve the existing JSONObject associated with that key directly from your root JSON object. Here's how to correct line 150:
Replace this:
JSONObject jsonPackageObject = new JSONObject(currentPackageKey); //line 150
With this:
JSONObject jsonPackageObject = jsonRootObject.getJSONObject(currentPackageKey);
This way, you're accessing the actual JSON object stored under the "screen_package" key in your root data, not trying to parse the key name as JSON.
Bonus: Make Your Code More Robust & Efficient
You can also simplify your code by skipping the loop through all package keys—since you already have the packageName parameter, you can directly check if that key exists in the root object and retrieve it immediately:
public void parseJSON(String jsonName, String packageName) { try { JSONObject jsonRootObject = new JSONObject(jsonName); if (jsonRootObject != null && jsonRootObject.length() > 0) { // Directly check if the target package exists in the root JSON if (jsonRootObject.has(packageName)) { JSONObject jsonPackageObject = jsonRootObject.getJSONObject(packageName); if (jsonPackageObject != null && jsonPackageObject.length() > 0) { Iterator<String> testNameKeys = jsonPackageObject.keys(); if (testNameKeys != null) { while (testNameKeys.hasNext()) { String currentTestNameKey = testNameKeys.next(); if (currentTestNameKey != null && currentTestNameKey.length() > 0) { // Retrieve the test object and extract details for your ArrayList JSONObject testObject = jsonPackageObject.getJSONObject(currentTestNameKey); String testName = testObject.getString("test_name"); String testType = testObject.getString("test_type"); // Add these details to your ArrayList here... } } } } } } } catch (JSONException e) { e.printStackTrace(); System.out.println("Exception caught : " + e.getLocalizedMessage()); } }
To add extra safety, you could use optJSONObject instead of getJSONObject—it returns null instead of throwing an exception if the key doesn't exist, which helps avoid unexpected crashes.
内容的提问来源于stack exchange,提问作者Gagan Batra

