2013-04-04 52 views
3

我使用的HTTP客戶端從Apache和我試圖解析從我從客戶得到的迴應JSON數組。解析來自HTTP響應JSON數組在Java中

這是我接收回來的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

如何在不工作?你在期待什麼?你得到了什麼? – John3136 2013-04-04 01:53:06

+1

陣列打印null – user2044754 2013-04-04 01:57:03

回答

3

的BufferedReader RD =新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent())) 對象OBJ = JSONValue.parse(rd.toString());

rd.toString()不會給你InputStream的內容對應於response.getEntity().getContent()。它反而給出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); 
+0

非常感謝,代碼工作! – user2044754 2013-04-04 02:12:29