W3docs

Simplest way to read JSON from a URL in Java

To read JSON from a URL in Java, you can use the readJsonFromUrl() method from the JSON simple library.

To read JSON from a URL in Java, you can use the JSONParser class from the JSON simple library. The JSON simple library is a lightweight Java library that provides simple and efficient methods for reading and writing JSON.

Here is an example of how you can use the JSONParser class to read JSON from a URL:

Add the following Maven dependency to your project:

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class Main {
    public static void main(String[] args) throws IOException, ParseException {
        URL url = new URL("http://example.com/json");
        JSONParser parser = new JSONParser();
        try (InputStreamReader reader = new InputStreamReader(url.openStream())) {
            JSONObject json = (JSONObject) parser.parse(reader);
            // Example: Extract a value
            String name = (String) json.get("name");
        }
    }
}

This code opens a connection to the URL, reads the JSON from the URL, and parses the JSON using the JSONParser class. The JSONObject class represents a JSON object, and you can use it to access the properties of the JSON object.

You can also use the IOUtils.toString() method from the Apache Commons IO library to read the JSON from the URL as a string:

Add the following Maven dependencies to your project:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.15.1</version>
</dependency>
import org.json.JSONObject;
import org.json.JSONTokener;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.URL;

public class Main {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://example.com/json");
        String json = IOUtils.toString(url, "UTF-8");
        JSONObject object = new JSONObject(new JSONTokener(json));
        // Example: Extract a value
        String name = object.getString("name");
    }
}

This code reads the JSON from the URL as a string, and then uses the JSONObject class from the org.json library to parse the JSON.

I hope this helps! Let me know if you have any other questions.