在Java中将JSON响应转换为String? [英] Getting JSON response into String in Java?

查看:115
本文介绍了在Java中将JSON响应转换为String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting responses in JSON format when I make API requests to an api.

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

I am getting this when I do the System.Out.Println of the response.

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]

但这不是预期的响应,响应应该是这样的,

But it is not the expected response, the response should be like this,

response: {
name:
class:
}

我正在使用Apache HTTP Client。

I am using Apache HTTP Client.

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

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

What should I do next in order to get the expected result? I just need a point in right direction.

推荐答案

你需要做这样的事情:

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

这篇关于在Java中将JSON响应转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆