JSON是一種輕量級的對象,下面是小編給大家深度解析一下JSON對象,感興趣的朋友跟小編一起來了解一下吧!
首先新建一個類工具類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();
}
}
以上就是對于JSON對象的深度解析了,更多相關內(nèi)容請繼續(xù)關注武林技術(shù)頻道。
新聞熱點
疑難解答
圖片精選