从Java中的HTTP响应中解析JSON数组

我正在使用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);