Android 解析JSON对象及实例说明
程序员文章站
2023-11-28 23:10:58
json是一种轻量级的对象,数据体积小,方便传输,易于解析!
首先新建一个类工具类jsonutil,用于获取请求返回的数据复制代码 代码如下:public class j...
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();
}
}
上一篇: 操作SD卡中文件夹和文件的方法