本文讲解的是最基本的JSON数据解析过程:
新创建一个json文件:如下图所示:
图1-1代码:
{
"human":[
{"id":"123","username":"xiaoming"},
{"id":"124","username":"xiaohong"},
{"id":"125","username":"xiaozhang"}
],
"title":"json数据解析"
}
把文件放在项目下的assets目录下,如下图所示:
图1-2开始编写代码,在.java文件中编写下面代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
try{
InputStreamReader isr=newInputStreamReader(getAssets().open("test.json"),"utf-8");//获取数据
BufferedReader br=newBufferedReader(isr);//接收数据
String line;
//创建一个字符串对象
StringBuilder builder=newStringBuilder();
while((line=br.readLine())!=null) {
builder.append(line);
}
br.close();
isr.close();
try{
JSONObject root=newJSONObject(builder.toString());
System.out.println("================================");
System.out.println("title="+root.get("title"));
JSONArray array=root.getJSONArray("human");
for(inti = 0; i < array.length(); i++) {
JSONObject lan=array.getJSONObject(i);
System.out.println("id="+lan.getInt("id"));
System.out.println("username="+lan.get("username"));
}
}catch(JSONException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}
//jso
}catch(UnsupportedEncodingException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}catch(IOException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}
}
效果如图所示:
图1-3本文由“你正哥来了”学习过程中笔记整理,纯属个人笔记资料,如有错误,请指教,望相互学习(Android ---你正哥来了)
网友评论