手记

http学习之json数据解析

对从服务器读取的数据String json进行json解析,并返回List<Person>数据
private List<Person> parseJson(String json){
//创建实体对象,以保存从json中获取到的数据,然后传给界面显示
List<Person> localPersons = new ArrayList<Person>();

JSONObject object = new JSONObject(json);
int result = object.getInt(“result”); //”result”字段需要和服务器中的json数据的result字//段一致

if(result == 1){
JSONArray personData = object.getJSONArray(“personData”); // personData为字段名

//对personData数组进行遍历

for(int I = 0;I <personData.length(); i++){

//创建本地Person实体对象 
Person localPerson = new Person();

JSONObject person = personData.get(i); //获取Person对象
String name = person.getString(“name”); //获取name字段值
int age = person.getInt(“age”); //获取age字段值
String url = person.getString(“url”); //获取url字段值

//保存解析出来的数据到本地实体对象
localPerson.setName(name);

localPerson.setAge(age);
localPerson.setUrl(url);

//创建本地SchoolInfo数组实体对象 
List<SchoolInfo> localSchoolInfos = new ArrayList< SchoolInfo >();
//获取SchoolInfo数组
JSONArray schoolInfos = person.getJSONArray(“schoolInof”);
for(int j =0; j<schoolInfos.length(); j++){
JSONObject school = schoolInfos.getJSONObject(j);
String schoolName = school.getString(“school_name”); //获取school_name字段

//创建本地SchoolInfo实体对象
SchoolInfo localSchoolInfo = new SchoolInfo();
localSchoolInfo.setSchoolName(schoolName);
localSchoolInfos.add(localSchoolInfo); //添加到localSchoolInfos数组

}

localPerson.setSchoolInfo(localSchoolInfos);

localPersons.add(localPerson); //将localPerson添加到localPersons数组
}

return localPersons;
}else{
//弹出错误提示
Toast.makeText(context, “error”, 1).show();
}
return null;

}

10人推荐
随时随地看视频
慕课网APP