我正在使用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);
这是我尝试过的代码,但它不起作用。我不确定该怎么做。感谢任何帮助。谢谢。
答案 0 :(得分:3)
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity()。getContent())) Object obj = JSONValue.parse(rd.toString());
rd.toString()
不会向您提供与InputStream
对应的response.getEntity().getContent()
的内容。它改为给出toString()
对象的BufferedReader
表示。尝试在控制台上打印它以查看它是什么。
相反,您应该阅读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);