Simple way to read json from a URL in Java

Asked 1 years ago, Updated 1 years ago, 76 views

It might be a stupid question, but what's the simplest way to parse and read JSON from a URL in Java? Groovy only needs a few lines of code, but all the Java examples I found are ridiculously long codes. Isn't there a simple sauce?

url json java

2022-09-22 22:13

1 Answers

It's not as short as you'd like, but...


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

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

public class JsonReader {

  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 JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
  }
}


2022-09-22 22:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.