How to read Json from a Java file with JSON Simple library?

1

I have the following code that throws me an error at runtime and I do not know where the problem is:

THE ERROR:

  

Exception reading configuration file java.lang.ClassCastException: org.json.simple.JSONObject can not 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 how my config.cfg looks in case you need it:

{"verb"  :"POST",
 "host"  :"192.169.3.243",
 "port"  :"8080",
 "method":"API/DOCUMENTS/"}

What I need is to get each JSON value within a JAVA variable so I can continue using them.

I'm using Java 8 and the JSON Simple library

    
asked by Nacho Zve De La Torre 16.07.2018 в 22:35
source

1 answer

2

The error indicates that the type that is being read is actually a JSONObject not a JSONArray. So it should be enough to put:

public static void readJson(){
      try {

        JSONParser parser = new JSONParser();
        Object object =  parser.parse(new FileReader("/home/incentivate/Desktop/config.cfg"));


          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);
    }
   }

Since your configuration file has only one element with several properties, a JSONArray is not necessary.

    
answered by 17.07.2018 / 05:20
source