Access JSON information from a URL by utilizing Java

I have read some answers like

Simplest way to read JSON from a URL in Java

but it did not work.

Okay, here is my code:

package day1;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class MainGet {

    public static void main(String[] args) {
        try {

            URL url = new URL("https://api.covid19api.com/summary");

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

            //Getting the response code
            int responsecode = conn.getResponseCode();

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

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

                //Write all the JSON data into a string using a scanner
                while (scanner.hasNext()) {
                    inline += scanner.nextLine();
                }

                //Close the scanner
                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);

                //Get the required object from the above created object
                JSONObject obj = (JSONObject) data_obj.get("Global");

                //Get the required data using its key
                System.out.println(obj.get("TotalRecovered"));

                JSONArray arr = (JSONArray) data_obj.get("Countries");

                for (int i = 0; i < arr.size(); i++) {

                    JSONObject new_obj = (JSONObject) arr.get(i);

                    if (new_obj.get("Slug").equals("albania")) {
                        System.out.println("Total Recovered: " + new_obj.get("TotalRecovered"));
                        break;
                    }
                }
            }

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

}

I want an example that can run in Eclipse. I have installed Gson and am using JDK11.

Here is my URL:

I want to read it into Java.

Thanks so much.

https://i.stack.imgur.com/26ZoB.png

I think I have added org.json to the path, but still have errors.

Answer №1

It seems like there was no error description provided in this instance. Based on the assumption of a JSON parsing error, it appears that the URL in question is returning a JSONArray instead of a JSONObject.

This solution resembles more of a copy and paste method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a 403 error while using the YouTube API

I have a setup where I display the latest uploaded YouTube videos on my channel. Everything seems to be working fine, but occasionally I encounter this error that causes my entire site to break! [phpBB Debug] PHP Warning: in file /my_youtube/functions.php ...

Is there a way to generate the specific JSON file format using my PHP script?

Here is the desired output: [ {"Airtel":{"v": 50.00}}, {"Hutch":{"v": 10.00}}, {"Idea":{"v": 10.00}}, {"TATA":{"v": 10.00}}, {"Vodafone":{"v": 20.00}}, {"Aircel":{"v": 15.00}} ] Since the data is retrieved from a MySQL database, it ...

Retrieve data from a JSON array using either JavaScript or PHP

Check out my code snippet: const newData = [{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]; Now, I need to extract specific details from this JSON data based on the 'new_no& ...

Breaking down a large JSON array into smaller chunks and spreading them across multiple files using PHP pagination to manage the

Dealing with a large file containing over 45,000 arrays can be challenging, especially on a live server with high traffic. To address this issue, I used the array_chunk($array, 1000) function to divide the arrays into 46 files. Now, my goal is to access a ...

Transfer image data in JSON format by compressing it into a base64 string from an Android device to a PHP web

I am attempting to upload an image (compressed in base64) as a JSONObject from an Android device to a web service using PHP. I have tried using HttpURLConnection with the POST method. Here is my code in Android: try { JSONObject params = new ...

Step by step guide on serializing two forms and an entire table

I have been attempting to serialize data from two forms and the entire table simultaneously. While the form data is successfully serialized, I am encountering difficulty in serializing the table records as well. Below is the code snippet of what I have att ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

Updating all data with CAKEPHP 2.0 and encoding it in JSON format

I am encountering a challenge with one of my controller functions. The function I have written is meant to update certain fields in my database by retrieving content from a decoded json_file, then re-encoding it for storage in the database. However, I am f ...

Contemplating the protection of an Android online platform

In the process of developing an Android app to connect to a http server, I have implemented a web service that sends JSON data to a PHP script on the server. This PHP script then accesses the desired database and inserts the JSON objects. However, my focu ...

Tips for exchanging JSON data between HTML and PHP using jQuery Ajax?

Hello there! I am just starting to learn PHP and jQuery, and I have been experimenting with some code to understand how things work. However, I seem to be having issues with sending data back and forth between my webpage and the PHP file on the server. Her ...

Storing an empty string in a Laravel database: A step-by-step guide

Below is the code snippet from my controller: public function addEmployer(Request $request) { $validator = UserValidations::validateEmployer($request->all()); if ($validator->fails()) { return response(['status' => false ...

Malformed PHP Array Structure

I am facing an issue with formatting the results of my query in an array and then encoding it into JSON. I want the data to be structured like this: array[0] = project1, project2, project3; array[1] = item1, item2, item3; However, currently, my data ...

Encountered CORS error when attempting to access the dynamic menu API after logging

Currently, I am working on an Angular 6 and Codeigniter project. In this project, the slider and navigation menu bar are being fetched dynamically through a REST API. Everything runs smoothly until the login process, where a CORS error is encountered. htt ...

Developing a JSON object with PHP

Is there a way in PHP to generate the following JSON structure? { "actors": [ { "name": "Brad Pitt", "description": "William Bradley 'Brad' Pitt is an American actor and film producer. He has received a Golden Globe Award, a Sc ...

Guide on obtaining JSON data in an android application through a PHP file?

I am a beginner in Android development and I have recently created a simple data fetching application. However, I am facing an issue where I am only able to retrieve the value of one variable from my PHP file, even though both variables are present in the ...

The function json_decode() in PHP fails to handle special characters like accents

When working with a JSON array that contains accented characters, such as üna, I use json_encode($array, JSON_UNESCAPED_UNICODE); to save it correctly. However, when trying to display this on a page using json_decode(), the accent causes the value not to ...

How can I send a JSON POST request using Delphi's TIdHttp

Has anyone had success using JSON with TIdHttp? I am having an issue where the PHP code always returns NULL in the $_POST, is there something I'm missing or doing wrong? Here's the Delphi source: http := TIdHttp.Create(nil); http.HandleRedirec ...

The json_decode function in PHP along with AJAX is returning an error stating "Invalid

Shown below is a sample json string data [{"ratetype":"Y","hotelPackage":"N","roomtype":"Deluxe Double Room","roombasis":",Complimentary Wi-Fi Internet, Breakfast, ","roomTypeCode":"0000015468","ratePlanCode":"0000120709","ratebands":{"validdays":"1111111 ...

"Upon parsing the JSON data, the decoder yielded a null

This question has been asked many times before, but I am still struggling to get it working. I have a JSON and when I dump the $TenentsAccessible output, it looks like this: string(71) "[{`TenantID`:`test.com`,`Name`:`12thdoor`}]" I need to extract the ...

"Error: The ajax call to the dojo endpoint is not retrieving the

Uncertain where I might have made a mistake as the code appears correct to me. I have confirmed that file.php -> mod_rewtite -> file.json is functioning properly by testing the JSON response through jQuery. However, the following code snippet immediately t ...