Home >Java >javaTutorial >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:
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!