I am using the HTTP client from Apache, and am trying to parse a JSON array from the response I get from the client.
This is an example of the JSON I receive back.
[{"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"}]
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);
Here is the code I have tried but it doesn't work. I am not really sure what to do. Any help is appreciated, thanks.
解决方案
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
Object obj=JSONValue.parse(rd.toString());
rd.toString() would not give you the content of that InputStream corresponding to response.getEntity().getContent(). It instead gives the toString() representation of a BufferedReader object. Try printing it on your console to see what it is.
Instead you should read the data from the BufferedReader as follows:
StringBuilder content = new StringBuilder();
String line;
while (null != (line = br.readLine()) {
content.append(line);
}
Then, you should parse the content to get the JSON array.
Object obj=JSONValue.parse(content.toString());
JSONArray finalResult=(JSONArray)obj;
System.out.println(finalResult);