I'm trying to read from a JSON file using json.simple java library but every time i run this code:
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(new FileReader("plugins/LogicGates/ands.json"));
Iterator i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
Block gate = (Block) obj.get("Gate");
Block inp1 = (Block) obj.get("Inp1");
Block inp2 = (Block) obj.get("Inp2");
ands.add(new And(gate, inp1, inp2));
}
it returns:
java.lang.ClassCastException: class java.lang.String cannot be cast to class org.json.simple.JSONObject (java.lang.String is in module java.base of loader 'bootstrap'; org.json.simple.JSONObject is in unnamed module of loader 'app')
Does anyone know why? Thanks in advance for any reply.
EDIT:
So I made the old code work somehow, here's how it looks now:
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(new FileReader("plugins/LogicGates/ands.json"));
Iterator i = jsonArray.iterator();
while (i.hasNext()) {
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse((String) i.next());
Block gate = (Block) obj.get("Gate");
Block inp1 = (Block) obj.get("Inp1");
Block inp2 = (Block) obj.get("Inp2");
ands.add(new And(gate, inp1, inp2));
}
But now I'm getting a completely different error:
Unexpected character (C) at position 8.
I was told that my JSON is not valid so here's the code that writes the JSON:
FileWriter writer = new FileWriter("plugins/LogicGates/ands.json");
JSONArray jsonArray = new JSONArray();
JSONObject obj = new JSONObject();
for(And a : ands) {
obj.put("Gate", a.getGate());
obj.put("Inp1", a.getInp1());
obj.put("Inp2", a.getInp2());
jsonArray.add(obj.toJSONString());
}
writer.write(jsonArray.toJSONString());
writer.close();