I have the following code that throws me an error at runtime and I don't know where the problem is:
THE ERROR:
Exception reading configuration file java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
My code:
public static void readJson(){
try {
JSONParser parser = new JSONParser();
JSONArray jsonArray = (JSONArray) parser.parse(new FileReader("/home/incentivate/Desktop/config.cfg"));
for (Object object : jsonArray)
{
JSONObject config = (JSONObject) object;
String verb = (String) config.get("verb");
System.out.println(verb);
String host = (String) config.get("host");
System.out.println(host);
String port = (String) config.get("port");
System.out.println(port);
String method = (String) config.get("method");
System.out.println(method);
}
} catch (Exception e) {
System.out.println("Excepcion leyendo fichero de configuracion " + e);
}
}
This is what my config.cfg looks like in case you need it:
{"verb" :"POST",
"host" :"192.169.3.243",
"port" :"8080",
"method":"API/DOCUMENTS/"}
What I need is to get each value of the JSON inside a JAVA variable so that I can continue using them.
I am using Java 8 and the Simple JSON library.
The error indicates that the type being read is actually a JSONObject not a JSONArray. So it should be enough to put:
Since your configuration file has only one element with several properties, a JSONArray is not necessary.