Convenient JSON Conversion from URL in Java
Many programmers seek a straightfoward method for extracting and parsing JSON data from internet sources using Java. This article provides an accessible solution to this common quandary.
Java's Simple JSON Retrieval
Despite the abundance of Java libraries, reading JSON from URLs can be an overly complex task. Here, we introduce a concise solution leveraging the org.json:json Maven artifact:
import org.json.JSONException; import org.json.JSONObject; public class JsonReader { public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { try (InputStream is = new URL(url).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { String jsonText = readAll(rd); return new JSONObject(jsonText); } } private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static void main(String[] args) throws IOException, JSONException { // Example URL String url = "https://graph.facebook.com/19292868552"; JSONObject json = readJsonFromUrl(url); System.out.println(json.toString()); System.out.println(json.get("id")); } }
This concise code enables you to effortlessly retrieve and interpret JSON data from URLs without excessive complications.
The above is the detailed content of How Can I Easily Parse JSON Data from a URL in Java?. For more information, please follow other related articles on the PHP Chinese website!