How to read JSON from a URL in Java with example

In this post, we will see How to read JSON from a URL in Java with examples.

Read JSON From a URL using Commons IO Library

To read JSON from a URL using the Commons IO library in Java, you can use the IOUtils class. Here’s an example.

import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.net.URL;

public class JsonReader {
    public static void main(String[] args) throws IOException {
        String url = "https://example.com/data.json";
        String json = IOUtils.toString(new URL(url), "UTF-8");
        System.out.println("JSON: " + json);
    }
}

In this example, we first define the URL that contains the JSON data. We then use the IOUtils.toString() method to read the JSON data from the URL into a string. We pass in the URL object and the encoding type (“UTF-8”) as arguments to the method. Finally, we print out the JSON data as a string.

Note that you will need to include the Commons IO library in your project’s classpath to use this approach. You can download the library from the Apache Commons website or use a dependency management tool like Maven or Gradle to include it in your project.

Read JSON from URL in Java with example Using the Jackson library

To read JSON using the Jackson library in Java, you can use the ObjectMapper class. Here’s an example:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URL;

public class JsonReader1 {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        URL url = new URL("https://example.com/data.json");
        MyDataObject data = mapper.readValue(url, MyDataObject.class);
        System.out.println("Data: " + data);
    }
}

In this example, we first define the URL that contains the JSON data. We then create an ObjectMapper object, which is used to parse the JSON data into a Java object. We use the readValue method of the ObjectMapper object to read the JSON data from the URL and parse it into a MyDataObject object. Finally, we print out the data object.

Note that you will need to include the Jackson library in your project’s classpath to use this approach. You can download the library from the Jackson website or use a dependency management tool like Maven or Gradle to include it in your project.

Also, you will need to replace MyDataObject with the name of the class that represents the JSON data you are reading. Make sure that the structure of the MyDataObject class matches the structure of the JSON data.

Read JSON Using the Gson library

To read JSON using the Gson library in Java, you can use the fromJson method of the Gson class. Here’s an example:

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class JsonReader {
    public static void main(String[] args) throws IOException {
        String url = "https://example.com/data.json";
        URL obj = new URL(url);
        BufferedReader in = new BufferedReader(new InputStreamReader(obj.openStream()));
        Gson gson = new Gson();
        MyDataObject data = gson.fromJson(in, MyDataObject.class);
        System.out.println("Data: " + data);
        in.close();
    }
}

In this example, we first define the URL that contains the JSON data. We then create a URL object and use an InputStreamReader to read the JSON data from the URL. We then create a BufferedReader to read the data from the input stream. We then create a Gson object and use its fromJson method to parse the JSON data into a MyDataObject object. Finally, we print out the data object and close the input stream.

Note that you will need to include the Gson library in your project’s classpath to use this approach. You can download the library from the Gson website or use a dependency management tool like Maven or Gradle to include it in your project.

Also, you will need to replace MyDataObject with the name of the class that represents the JSON data you are reading. Make sure that the structure of the MyDataObject class matches the structure of the JSON data.

Read JSON Using the org.json library

To read JSON using the org.json library in Java, you can create a JSONObject from the JSON data retrieved from the URL. Here’s an example.

import org.json.JSONObject;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JsonReader {
    public static void main(String[] args) throws IOException {
        String url = "https://example.com/data.json";
        String jsonText = readUrl(url);
        JSONObject json = new JSONObject(jsonText);
        System.out.println("JSON: " + json.toString());
    }
    
    private static String readUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        return new String(Files.readAllBytes(Paths.get(url.getFile())), StandardCharsets.UTF_8);
    }
}

In this example, we first define the URL that contains the JSON data. We then use the readUrl method to read the JSON data from the URL and return it as a string. We create a JSONObject from the JSON data string and print out the JSON object as a string.

The readUrl method reads the JSON data from the URL using the Files.readAllBytes method and returns it as a string. Note that we need to pass in the file path of the URL using the getPath method of the URL object.

Note that you will need to include the org.json library in your project’s classpath to use this approach. You can download the library from the org.json website or use a dependency management tool like Maven or Gradle to include it in your project.

Read JSON from URL in Java with example Using the JsonPath library

To read JSON using the JsonPath library in Java, you can use the JsonPath class to extract data from the JSON object. Here’s an example:

import com.jayway.jsonpath.JsonPath;
import java.io.IOException;
import java.net.URL;

public class JsonReader {
    public static void main(String[] args) throws IOException {
        String url = "https://example.com/data.json";
        Object json = JsonPath.read(new URL(url), "$");
        System.out.println("JSON: " + json.toString());
    }
}

In this example, we first define the URL that contains the JSON data. We then use the JsonPath.read method to read the JSON data from the URL and parse it into an Object representing the JSON data. We print out the JSON object as a string.

Note that you will need to include the JsonPath library in your project’s classpath to use this approach. You can download the library from the JsonPath GitHub page or use a dependency management tool like Maven or Gradle to include it in your project.

Also, note that the second argument to the JsonPath.read method specifies the path to the data you want to extract from the JSON object. You can use JsonPath expressions to specify the path to the data you want to extract. For example, you can use $.propertyName to extract a property from the root object, or $.propertyName[n] to extract the nth element of an array.

Using the Java 11 HttpClient library

To read JSON using the Java 11 HttpClient library, you can use the HttpResponse.BodyHandlers.ofString() method to retrieve the response body as a string, and then use a JSON library to parse the string into a Java object. Here's an example:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class JsonReader {
    public static void main(String[] args) throws Exception {
        String url = "https://example.com/data.json";
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        String jsonText = response.body();
        // Use a JSON library to parse the JSON string into a Java object
        System.out.println("JSON: " + jsonText);
    }
}

In this example, we first define the URL that contains the JSON data. We then create an HttpClient object and an HttpRequest object that specifies the URL to retrieve. We use the HttpClient.send method to send the request and retrieve the response. We use the HttpResponse.BodyHandlers.ofString() method to specify that we want to retrieve the response body as a string. We then use a JSON library to parse the string into a Java object.

Note that the HttpClient library was introduced in Java 11, so you will need to be using Java 11 or later to use this approach.

Also note that you will need to include the JSON library in your project’s classpath to parse the JSON string into a Java object. You can use any of the JSON libraries discussed in the previous answers to parse the JSON string.

That’s all about How to read JSON from a URL in Java with example.

See docs.

More post.