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,此主机名是模拟器设定的特定的访问自己电脑的主机名,它记录了你的电脑的名称。
另外:获取数据需要将下面的方法封装到一个新线程中,不能放在程序主线程当中!
代码如下:
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();
}
}