简体   繁体   中英

JSON-SIMPLE Can't cast to object to read through array

I'm trying to use JSON-Simple to read a configuration file that's in JSON using the following code

    File f = new File("config.json");
    JSONParser parser = new JSONParser();
    try {
        int i;
        StringBuilder out = new StringBuilder();
        FileReader reader = new FileReader(f);
        while ((i = reader.read()) != -1) {
            out.append((char) i);
        }
        JSONArray array = (JSONArray) JSONValue.parse(out.toString());

    } catch (Exception e) {
        System.out.println(e.toString());
    }

or

    File f = new File("config.json");
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(new FileReader(f));
        JSONObject jsonObject = (JSONObject) obj;

        JSONArray array = (JSONArray) jsonObject.get("module");
        Iterator<String> itreator = array.iterator();
        while (itreator.hasNext()) {
            System.out.println(itreator.next());
        }
    } catch (FileNotFoundException fnf) {
        fnf.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

but both are returning the error

org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

however when doing

    File f = new File("config.json");
    try {
        System.out.println(JSONValue.parse(new FileReader(f)));
    } catch (Exception e) {
        System.out.println(e.toString());
    }

it returns the file's contents.

The config file can be seen here: http://pastebin.com/5xJTHSwj

module tag in your config file isn't array. JSON array starts with [
eg
"module" : [{prop : "One"},{prop : "Two"}]

Use this code instead

JSONObject moduleObject= (JSONObject ) jsonObject.get("module");  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM