Home >Java >javaTutorial >How Can I Easily Read JSON Data from a URL in Java?

How Can I Easily Read JSON Data from a URL in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 22:19:10215browse

How Can I Easily Read JSON Data from a URL in Java?

Easiest JSON Reading from URL in Java

In Java, reading and parsing JSON from a URL can be straightforward with the help of a third-party library. Consider using the org.json:json Maven artifact for its brevity.

The simplest approach involves:

  1. Importing the dependency: Include the dependency in your Maven project to access the JSON parsing functionality.
  2. Using the readJsonFromUrl method: This method takes a URL as a parameter and returns a JSONObject after reading and parsing the JSON content at that URL.

A concise example using this dependency is provided below:

import org.json.JSONException;
import org.json.JSONObject;

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

public class JsonReader {

    public static void main(String[] args) throws IOException, JSONException {
        // Read the JSON
        JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");

        // Process the JSON
        System.out.println(json.toString()); // Print the entire JSON as a string
        System.out.println(json.get("id")); // Access a specific property by name
    }

    private static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        // Open the URL
        URL urlObject = new URL(url);

        // Read the JSON
        InputStream is = urlObject.openStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String jsonText = rd.readLine();

        // Parse the JSON
        JSONObject json = new JSONObject(jsonText);

        // Cleanup
        is.close();
        rd.close();

        return json;
    }
}

This snippet reads the JSON from the supplied URL, parses it into a JSONObject, and demonstrates how to retrieve a specific property by name. It offers a compact and convenient way to handle JSON data from a URL in Java.

The above is the detailed content of How Can I Easily Read JSON Data from a URL in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn