Android 解析JSON對象及執行個體說明

來源:互聯網
上載者:User

JSON是一種輕量級的對象,資料體積小,方便傳輸,易於解析!

首先建立一個類工具類JsonUtil,用於擷取請求返回的資料

複製代碼 代碼如下: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時表示請求資料成功
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();
}
}

擷取資料並解析資料:
注:模擬器訪問自己電腦上的網站不能用localhost:8080或者127.0.0.1:8080,因為模擬器預設將模擬器本身設定為localhost,所以如果設定為這樣的方式就將訪問模擬器本身。我們需要將主機名稱修改為10.0.2.2,此主機名稱是模擬器設定的特定的訪問自己電腦的主機名稱,它記錄了你的電腦的名稱。
另外:擷取資料需要將下面的方法封裝到一個新線程中,不能放在程式主線程當中!複製代碼 代碼如下: /* 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);
// 擷取學生數組 --> students:[{name:'Livingstone',age:25},{name:'LS',age:26}]
JSONArray jArr = jObj.getJSONArray("students");
// 擷取班級 --> class:'09GIS班'
String classname = jObj.getString("class");
// 根據索引擷取第一個學生的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();
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.