Skip to content
Advertisement

REST api with only 1 object java

This code makes use of JSON-simple for connecting to an api:

try {

            URL url = new URL("https://api.kanye.rest/");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();

            int responsecode = conn.getResponseCode();

            if (responsecode != 200) {
                throw new RuntimeException("HttpResponseCode: " + responsecode);
            } else {

                String inline = "";
                Scanner scanner = new Scanner(url.openStream());

                while (scanner.hasNext()) {
                    inline += scanner.nextLine();
                }

                scanner.close();

                //Using the JSON simple library parse the string into a json object
                JSONParser parse = new JSONParser();
                JSONObject data_obj = (JSONObject) parse.parse(inline);


                JSONObject obj = (JSONObject) data_obj.get("quote");

                commandSender.sendMessage("<Kanye> " + obj);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

Nothing get sent out though. Only warning is this:

[15:15:49 WARN]: 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')

[15:15:49 WARN]:    at api-1.0.jar//net.ntdi.api.commands.kanyeCommand.perform(kanyeCommand.java:131)```

Advertisement

Answer

Casting to a string is the solution.

String quote = (String) data_obj.get("quote")
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement