Java 使用 JSON.org 解析器从 HttpClient 请求解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23743370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:57:45  来源:igfitidea点击:

Parsing JSON from HttpClient request using JSON.org parser

javajsonparsingxpagesapache-httpclient-4.x

提问by Thomas Adrian

I am trying to parse JSON using a Notes agent, JSON is fetched using Apache HttpClient.

我正在尝试使用 Notes 代理解析 JSON,使用 Apache HttpClient 获取 JSON。

Here is the code that return the JSON

这是返回 JSON 的代码

import lotus.domino.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

      Session session = getSession();
      AgentContext agentContext = session.getAgentContext();

      HttpClient client = HttpClientBuilder.create().build();
      HttpGet request = new HttpGet("http://api.acme.com/customer");
      request.addHeader("accept", "application/json");
      request.addHeader("Host", "api.acme.com");
      request.addHeader("X-Api-Version", "1.0");
      request.addHeader("Authorization", "Basic ...");

      HttpResponse response = client.execute(request);       

The JSON Looks like this.

JSON 看起来像这样。

[ 
  { 
    "id": 123456, 
    "insertDate": "2014-05-12T16:51:38.343", 
    "read": false, 
    "site": "acme.com", 
    "Email": "[email protected]", 
    "location": "/customer/1212?v=1.0" 
  } 
] 

I have tried to use JSONObjectand JSONArrayfrom JSON.org but could not get it to work I need some example code from the json.org package or other ways to parse the json.

我曾尝试从 JSON.org使用JSONObjectJSONArray但无法使其工作 我需要来自 json.org 包的一些示例代码或其他方法来解析 json。

采纳答案by Tristan

You can get the JSON from the Entity in the HttpResponse using HttpResponse#getEntity. Once you have that, then just create a new JSONArray and iterate the array to access the values in your JSON object:

您可以使用HttpResponse#getEntity从 HttpResponse 中的实体获取 JSON 。一旦你有了它,那么只需创建一个新的 JSONArray 并迭代数组以访问 JSON 对象中的值:

String json = IOUtils.toString(response.getEntity().getContent());
JSONArray array = new JSONArray(json);
for (int i = 0; i < array.length(); i++) {
    JSONObject object = array.getJSONObject(i);
    log.info("the id is {}", object.getInt("id"));
    log.info("the insertDate is {}", object.getString("insertDate"));
    log.info("read is {}", object.getBoolean("read"));
    log.info("the site is {}", object.getString("site"));
    log.info("the Email is {}", object.getString("Email"));
    log.info("the location is {}", object.getString("location"));
}

I saved the JSON in a JSONBlob at http://jsonblob.com/537a43bfe4b047fa2ef5f15dand created a unit test that requests that JSON:

我将 JSON 保存在http://jsonblob.com/537a43bfe4b047fa2ef5f15d的 JSONBlob 中,并创建了一个请求该 JSON 的单元测试:

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;

@Slf4j
public class JsonTest {
    @Test
    public void test() throws Exception {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet("http://jsonblob.com/api/jsonBlob/537a43bfe4b047fa2ef5f15d");
        request.addHeader("accept", "application/json");
        HttpResponse response = client.execute(request);
        String json = IOUtils.toString(response.getEntity().getContent());
        JSONArray array = new JSONArray(json);
        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            log.info("the id is {}", object.getInt("id"));
            log.info("the insertDate is {}", object.getString("insertDate"));
            log.info("read is {}", object.getBoolean("read"));
            log.info("the site is {}", object.getString("site"));
            log.info("the Email is {}", object.getString("Email"));
            log.info("the location is {}", object.getString("location"));
        }
    }
}

And the output from running it is:

运行它的输出是:

11:23:19.508 [main] INFO  JsonTest - the id is 123456
11:23:19.516 [main] INFO  JsonTest - the insertDate is 2014-05-12T16:51:38.343
11:23:19.516 [main] INFO  JsonTest - read is false
11:23:19.516 [main] INFO  JsonTest - the site is acme.com
11:23:19.516 [main] INFO  JsonTest - the Email is [email protected]
11:23:19.516 [main] INFO  JsonTest - the location is /customer/1212?v=1.0

I used the IOUtilsclass to convert the InputStream from the HttpResponse Entity, but this can be done anyway you like (and converting it like I did may not be the best idea depending on how big the JSON is).

我使用IOUtils类从 HttpResponse 实体转换 InputStream ,但这可以按您喜欢的方式完成(并且像我一样转换它可能不是最好的主意,这取决于 JSON 有多大)。