gpt4 book ai didi

java - 在 Java 中从 HTTP 响应解析 JSON 数组

转载 作者:可可西里 更新时间:2023-11-01 16:11:18 26 4
gpt4 key购买 nike

我正在使用来自 Apache 的 HTTP 客户端,并试图从我从客户端获得的响应中解析一个 JSON 数组。

这是我收到的 JSON 示例。

 [{"created_at":"2013-04-02T23:07:32Z","id":1,"password_digest":"$2a$10$kTITRarwKawgabFVDJMJUO/qxNJQD7YawClND.Hp0KjPTLlZfo3oy","updated_at":"2013-04-02T23:07:32Z","username":"eric"},{"created_at":"2013-04-03T01:26:51Z","id":2,"password_digest":"$2a$10$1IE6hR4q5jQrYBtyxMJJBOGwSPQpg6m5.McNDiSIETBq4BC3nUnj2","updated_at":"2013-04-03T01:26:51Z","username":"Sean"}]

我正在使用 http://code.google.com/p/json-simple/作为我的 json 库。

        HttpPost httppost = new HttpPost("SERVERURL");
httppost.setEntity(input);
HttpResponse response = httpclient.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))

Object obj=JSONValue.parse(rd.toString());
JSONArray finalResult=(JSONArray)obj;
System.out.println(finalResult);

这是我试过但不起作用的代码。我不太确定该怎么做。感谢任何帮助,谢谢。

最佳答案

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())) Object obj=JSONValue.parse(rd.toString());

rd.toString() 不会为您提供对应于 response.getEntity().getContent()InputStream 的内容。相反,它给出了 BufferedReader 对象的 toString() 表示。尝试在您的控制台上打印它以查看它是什么。

您应该从 BufferedReader 中读取数据,如下所示:

StringBuilder content = new StringBuilder();
String line;
while (null != (line = br.readLine()) {
content.append(line);
}

然后,您应该解析内容以获取 JSON 数组。

Object obj=JSONValue.parse(content.toString());
JSONArray finalResult=(JSONArray)obj;
System.out.println(finalResult);

关于java - 在 Java 中从 HTTP 响应解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15801247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com