这可能是一个愚蠢的问题,但是在Java中从URL读取和解析JSON的最简单的方法是什么?

在Groovy中,这只是几行代码的问题。我发现Java示例长得离谱(并且有巨大的异常处理块)。

我所要做的就是阅读这个链接的内容。


当前回答

使用Maven工件。我得到了以下代码,我认为这是相当短的。不是尽可能短,但仍然可用。

package so4308554;

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

其他回答

使用HttpClient获取URL的内容。然后使用来自json.org的库来解析JSON。我在许多项目中使用过这两个库,它们都很健壮,使用起来很简单。

除此之外,你可以尝试使用Facebook API java库。我在这方面没有任何经验,但有一个关于在java中使用Facebook API的堆栈溢出的问题。您可能希望将RestFB视为使用库的一个不错选择。

如果你不介意使用几个库,它可以在一行中完成。

包括Apache Commons IOUtils和json.org库。

JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8")));

Maven的依赖:

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.7</version>
</dependency>

我发现这是迄今为止最简单的方法。

使用这个方法:

public static String getJSON(String url) {
        HttpsURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpsURLConnection) u.openConnection();

            con.connect();


            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            return sb.toString();


        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

像这样使用它:

String json = getJSON(url);
JSONObject obj;
   try {
         obj = new JSONObject(json);
         JSONArray results_arr = obj.getJSONArray("results");
         final int n = results_arr.length();
            for (int i = 0; i < n; ++i) {
                // get the place id of each object in JSON (Google Search API)
                String place_id = results_arr.getJSONObject(i).getString("place_id");
            }


   }

最简单的方法: 使用gson,谷歌自己的goto json库。https://code.google.com/p/google-gson/

这是一个样品。我到这个免费的地理定位器网站,解析json,显示邮政编码。(只要把这些东西放在主方法中测试就可以了)

    String sURL = "http://freegeoip.net/json/"; //just a string

    // Connect to the URL using java's native library
    URL url = new URL(sURL);
    URLConnection request = url.openConnection();
    request.connect();

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode

我不确定这是否有效,但这是一种可能的方法:

使用url. openstream()从url读取json,并将内容读入字符串。

用这个字符串构造一个JSON对象(更多信息请访问json.org)

JSONObject(java.lang.String source)
      Construct a JSONObject from a source JSON text string.