对于JSon数据的解析,android内部有提供相应的方法,但是Google提供的JSon解析包GSon使用起来也比较简便,下面介绍一下这个包的解析方法:
1.首先我们来看一下JSon的数据封装:
{"result":1,
"personData":[{"name":"nate","age":12,"url":"http://www.baidu.com",
"schoolInfo":[{"school_name":"清华"},{"school_name":"北大"}]},
{"name":"jack","age":12,"url":"http://www.sina.com",
"schoolInfo":[{"school_name":"aaa"},{"school_name":"bbb"}]}]}
2.需要生成这个JSon文件也很简单,首先用类来封装这些数据,提供get和set方法即可,如果是数据集合,那么久用List来封装,还要注意的是变量名是和JSon数据的键值对应的:
import java.util.List;
public class Person {
private String name;
private int age;
private String url;
private List<SchoolInfo> schoolInfo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<SchoolInfo> getSchoolInfo() {
return schoolInfo;
}
public void setSchoolInfo(List<SchoolInfo> schoolInfo) {
this.schoolInfo = schoolInfo;
}
}
public class SchoolInfo {
private String school_name;
public String getSchool_name() {
return school_name;
}
public void setSchool_name(String school_name) {
this.school_name = school_name;
}
}
import java.util.List;
public class Result {
private int result;
private List<Person> personData;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public List<Person> getPersonData() {
return personData;
}
public void setPersonData(List<Person> personData) {
this.personData = personData;
}
}
接下来就可以使用gson包提供的Gson类进行import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
public class TestJson {
public static void main(String[] args) {
// TODO Auto-generated method stub
Result result = new Result();
result.setResult(1);
List<Person> list = new ArrayList<Person>();
result.setPersonData(list);
Person person1 = new Person();
person1.setName("nate");
person1.setAge(12);
person1.setUrl("http://www.baidu.com");
List<SchoolInfo> schools = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo1 = new SchoolInfo();
schoolInfo1.setSchool_name("清华");
SchoolInfo schoolInfo2 = new SchoolInfo();
schoolInfo2.setSchool_name("北大");
schools.add(schoolInfo1);
schools.add(schoolInfo2);
person1.setSchoolInfo(schools);
list.add(person1);
Person person2 = new Person();
person2.setName("jack");
person2.setAge(12);
person2.setUrl("http://www.sina.com");
List<SchoolInfo> schools1 = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo3 = new SchoolInfo();
schoolInfo3.setSchool_name("aaa");
SchoolInfo schoolInfo4 = new SchoolInfo();
schoolInfo4.setSchool_name("bbb");
schools1.add(schoolInfo3);
schools1.add(schoolInfo4);
person2.setSchoolInfo(schools1);
list.add(person2);
Gson gson = new Gson();
System.out.println(gson.toJson(result));
}
}
gson下载链接
http://yunpan.cn/c3whd59gPps3Q 访问密码 d317