如何将HttpEntity转换为JSON?

我想从Web服务中检索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) {

}

不幸的是,我不知道如何转换HttpEntity为JSONObject。

这是我的JSON(摘录):

{

"names": [

{

"name": "Zachary"

},

{

"name": "Wyatt"

},

{

"name": "William"

}

]

}

回答:

您可以将字符串转换为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) {

}

以上是 如何将HttpEntity转换为JSON? 的全部内容, 来源链接: utcz.com/qa/432016.html

回到顶部