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

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

Linda Hamilton
Release: 2024-12-13 13:22:13
Original
781 people have browsed it

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

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"));
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template