Android 如何将 HttpEntity 转换为 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10804466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert HttpEntity into JSON?
提问by user1170330
I want to retrieve JSON from a web-service and parse it then.
Am I on the right way?
我想从网络服务中检索 JSON 并解析它。
我在正确的路上吗?
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
// parsing JSON
}
} catch (Exception e) {
}
Unfortunately I don't know how to convert HttpEntity
into a JSONObject.
不幸的是,我不知道如何转换HttpEntity
为 JSONObject。
This is my JSON (extract):
这是我的 JSON(摘录):
{
"names": [
{
"name": "Zachary"
},
{
"name": "Wyatt"
},
{
"name": "William"
}
]
}
回答by ρяσ?ρ?я K
You can convert string to json as:
您可以将字符串转换为 json 为:
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
String retSrc = EntityUtils.toString(entity);
// parsing JSON
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
JSONArray tokenList = result.getJSONArray("names");
JSONObject oj = tokenList.getJSONObject(0);
String token = oj.getString("name");
}
}
catch (Exception e) {
}
回答by Cristian
Use the entity.getContent() to get the InputStream and convert it to String.
使用 entity.getContent() 获取 InputStream 并将其转换为 String。
回答by Kumar Vivek Mitra
Try this
尝试这个
public String getMyFeed(){
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclien.execute(httpget);
HttpEntity entity = response.getEntity();
HttpInputStream content = entity.getContent();
StatusLine sl = response.getStatusLine();
int statCode = sl.getStatusCode()
if (statCode ==200){
// process it
}
}
String readFeed = getMyFeed();
JSONArray jArr = new JSONArray(readFeed);
for(int i=0 ; i<jArr.length ; i++)
JSONObject jObj = jArr.getJSONObject(i);