java请求json数组,从解析Java中的HTTP响应JSON数组

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值