Domanda

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

È stato utile?

Soluzione

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

Use this code instead

JSONObject moduleObject= (JSONObject ) jsonObject.get("module");  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top