最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android 解析JSON對象及實例說明

 更新時間:2013年04月19日 17:24:38   作者:  
本篇文章小編為大家介紹,Android 解析JSON對象及實例說明。需要的朋友參考下

JSON是一種輕量級的對象,數(shù)據(jù)體積小,方便傳輸,易于解析!

首先新建一個類工具類JsonUtil,用于獲取請求返回的數(shù)據(jù)

復制代碼 代碼如下:

public class JsonUtil {
 private static final String TAG = "JSONUTIL";
 public static JSONObject getJSON(String url) throws Exception {
  return new JSONObject(getRequest(url));
 }
 protected static String getRequest(String url) {
  return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
 }
 protected static String getRequest(String url, DefaultHttpClient client) {
  String result = null;
  int statusCode = 0;
  HttpGet httpGet = new HttpGet(url);
  try {
   HttpResponse httpResponse = client.execute(httpGet);
   statusCode = httpResponse.getStatusLine().getStatusCode();// statusCode為200時表示請求數(shù)據(jù)成功
   result = parseInputStream(httpResponse.getEntity());
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   httpGet.abort();
  }
  return result;
 }
 private static String parseInputStream(HttpEntity entity) {
  StringBuilder sb = null;
  try {
   sb = new StringBuilder("");
   InputStream inputStream = entity.getContent();
   int length = 0;
   byte[] buffer = new byte[1024];
   while ((length = inputStream.read(buffer)) > -1) {
    sb.append(new String(buffer, 0, length));
   }
   return sb.toString();
  } catch (IllegalStateException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return sb.toString();
 }
}

獲取數(shù)據(jù)并解析數(shù)據(jù):
注:模擬器訪問自己電腦上的網(wǎng)站不能用localhost:8080或者127.0.0.1:8080,因為模擬器默認將模擬器本身設定為localhost,所以如果設置為這樣的方式就將訪問模擬器本身。我們需要將主機名修改為10.0.2.2,此主機名是模擬器設定的特定的訪問自己電腦的主機名,它記錄了你的電腦的名稱。
另外:獲取數(shù)據(jù)需要將下面的方法封裝到一個新線程中,不能放在程序主線程當中!
復制代碼 代碼如下:

 /* http://10.0.2.2:8080/index.jsp
  * { students:[{name:'Livingstone',age:25},{name:'LS',age:26}], class:'09GIS' }
  */
 private void Livingstone() {
  try {
   String URL = "http://10.0.2.2:8080/index.jsp";
   // 獲取后臺返回的JSON對象 --> { students:[{name:'Livingstone',age:25},{name:'LS',age:26}],class:'09GIS班' }
   JSONObject jObj = JsonUtil.getJSON(URL);
   // 獲取學生數(shù)組 --> students:[{name:'Livingstone',age:25},{name:'LS',age:26}]
   JSONArray jArr = jObj.getJSONArray("students");
   // 獲取班級 --> class:'09GIS班'
   String classname = jObj.getString("class");
   // 根據(jù)索引獲取第一個學生的JSON對象 --> {name:'Livingstone',age:25}
   JSONObject j1 = jArr.getJSONObject(0);

   String studentInfo = jArr.length() + "個學生" + j1.getString("name")
     + j1.getInt("age");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }


相關文章

最新評論

海晏县| 广平县| 夏河县| 登封市| 武陟县| 闸北区| 普格县| 甘谷县| 吉水县| 义乌市| 柳江县| 宁陕县| 长武县| 阳曲县| 鲁甸县| 交城县| 巫山县| 个旧市| 景宁| 镇原县| 涡阳县| 交城县| 三亚市| 鹰潭市| 吐鲁番市| 乡城县| 内黄县| 台南县| 安阳市| 海晏县| 沧州市| 民县| 民勤县| 芜湖市| 开阳县| 安福县| 巴南区| 河北区| 宝清县| 宜章县| 额敏县|