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

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

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


当前回答

Oracle文档描述了如何操作

一个HttpRequest被构建,然后 由HttpClient发送给URL

只需几行代码,通过使用Java类库。把这段代码放到你的main方法中:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("http://example.com/"))
      .build();
client.sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

响应由JSON对象{…},并可在您的申请中进一步处理。 在这里我把它打印到控制台,只是为了确认它是有效的:

System.out.println(request);

这可用于Java版本11+

其他回答

我已经用最简单的方式完成了json解析器,下面就是

package com.inzane.shoapp.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            System.out.println(line);
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        System.out.println("error on parse data in jsonparser.java");
    }

    // return JSON String
    return jObj;

}
}

该类从url返回json对象

当你想要json对象时,你只需调用这个类和Activity类中的方法

我的代码在这里

String url = "your url";
JSONParser jsonParser = new JSONParser();
JSONObject object = jsonParser.getJSONFromUrl(url);
String content=object.getString("json key");

这里的“json key”指的是json文件中的键

这是一个简单的json文件示例

{
    "json":"hi"
}

这里“json”是键,“hi”是值

这将使您的json值字符串内容。

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

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

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

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

最简单的方法: 使用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

这很简单,使用jersey-client,只需要包含这个maven依赖:

<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
  <version>2.25.1</version>
</dependency>

然后使用下面的例子调用它:

String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);

然后使用谷歌的Gson来解析JSON:

Gson gson = new Gson();
Type gm = new TypeToken<CoinDeskMessage>() {}.getType();
CoinDeskMessage cdm = gson.fromJson(json, gm);

我想在这里添加一个更新的答案,因为最近对JDK的更新使读取HTTP URL的内容变得更容易了。 正如其他人所说,您仍然需要使用JSON库来进行解析,因为JDK目前还不包含JSON库。 下面是一些最常用的Java JSON库:

组织。杰伦 FasterXML Jackson 格森

要从URL检索JSON,这似乎是严格使用JDK类的最简单方法(但对于大型有效负载,可能不是您想要做的事情),Java 9介绍了:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InputStream.html#readAllBytes()

try(java.io.InputStream is = new java.net.URL("https://graph.facebook.com/me").openStream()) {
    String contents = new String(is.readAllBytes());
}

例如,使用GSON库解析JSON

com.google.gson.JsonElement element = com.google.gson.JsonParser.parseString(contents); //from 'com.google.code.gson:gson:2.8.6'