在Java中将JSON响应转换为String?

时间:2012-10-04 20:39:17

标签: java json http

当我向api发出API请求时,我收到了JSON格式的响应。

当我执行回复的System.Out.Println时,我得到了这个。

HTTP/1.1 200 OK [Date: Thu, 04 Oct 2012 20:33:18 GMT, Server: Apache/1.3.33 (Unix) PHP/4.4.0, Cache-control: no-cache, must-revalidate, no-cache="Set-Cookie", private, Expires: Fri, 01 Jan 1990 00:00:00 GMT, Pragma: no-cache, X-CreationTime: 0.051, Set-Cookie: DT=1349382798:29998:365-l4; path=/; expires=Fri, 01-Jan-2020 00:00:00 GMT; domain=.wunderground.com, Connection: close, Transfer-Encoding: chunked, Content-Type: application/json; charset=UTF-8]

但这不是预期的反应,反应应该像这样,

response: {
name:
class:
}

我正在使用Apache HTTP Client。

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url); 
HttpResponse response = httpclient.execute(httpget);
System.out.println(response);

为了获得预期的结果,我该怎么做?我只需要一个正确的方向点。

2 个答案:

答案 0 :(得分:3)

我在这里回答我自己的问题:

经过对Apache网站的一些研究,我发现了这个:

HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));

相信我,它更容易,就像魅力一样。

答案 1 :(得分:2)

你需要做这样的事情:

HttpResponse response = httpclient.execute(httpget);
StringBuilder sb = new StringBuilder();
DataInputStream in = new DataInputStream(response.getEntity().getContent()); 
String line;     
while ((line = in.readLine()) != null) { 
    sb.append(line);
} 
in.close(); 
String json = sb.toString(); 
相关问题