栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android 解析JSON对象及实例说明

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 解析JSON对象及实例说明

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();
  }
 }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/165474.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号