我想从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。
HttpEntity
这是我的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) { }