无法从 JSON 文件中读取数据

Unable to read the data from JSON File

import java.io.FileNotFoundException;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class testdata {
    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
        JSONParser parser = new JSONParser(); 
        try { System.out.println("Reading JSON file from Java program"); 
        FileReader fileReader = new FileReader("C:\Users\...\testdata.json"); 
        JSONObject json = (JSONObject) parser.parse(fileReader); 
        String title = (String) json.get("Attachment__c"); 
        System.out.println("title: " + title); 
                } catch (Exception ex) 
        { ex.printStackTrace(); }
}}

尝试使用上述代码时,我收到以下错误。

java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject at testdata.main(testdata.java:33)

我的JSON文件

您可以将其解析为对象类型,然后检查 您拥有的 json 结构的类型 Array对象.

System.out.println("Reading JSON file from Java program");
FileReader fileReader = new FileReader("C:\Users\...\testdata.json");
Object jsonObj = parser.parse(fileReader);
if (jsonObj instanceof JSONObject) {
    // its an object
} else if (jsonObj instanceof JSONArray) {
    JSONArray array = (JSONArray) jsonObj;
    array.forEach(i -> {
        JSONObject obj = (JSONObject) i;
        JSONObject attributes = (JSONObject) obj.get("attributes");

        System.out.println(attributes.get("Attachment__c"));
   });
} else {
    // something else
}
public static void main(String[] args) throws FileNotFoundException {
    JSONParser parser = new JSONParser();
    try {
        FileReader fileReader = new FileReader("C:\Users\Priya\testdata.json");
        Object jsonObj = parser.parse(fileReader);
        if (jsonObj instanceof JSONObject) {

        } else if (jsonObj instanceof JSONArray) {
            JSONArray array = (JSONArray) jsonObj;
            System.out.println(array.size());
            for (int i = 0; i < array.size(); i++) {
                String attachmentValue = (String) ((JSONObject) array.get(i)).get("Attachment__c");
        }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}