封裝類Attribute: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class Attribute { private int id; private String name; priva
封裝類Attribute:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class Attribute {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId( int id) {
this .id = id;
}
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;
}
}
|
另一個封裝類GsonDataAnalysis:
1 2 3 4 5 6 7 8 9 10 11 12 |
public class GsonDataAnalysis {
private List<Attribute> list;
public List<Attribute> getList() {
return list;
}
public void setList(List<Attribute> list) {
this .list = list;
}
}
|
測試類Main方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/**
* Gson解析json數據
* @author ForeverLover
* @version 2015-04-19
*/
public class GsonTest {
public static void main(String[] args) {
String sTotalString = "{\"list\": [" +
"{\"id\":\"1\",\"name\":\"Tom\",\"age\":\"12\"}," +
"{\"id\":\"2\",\"name\":\"Marry\",\"age\":\"18\"}" +
"]}" ;
Gson gson = new Gson();
GsonDataAnalysis gda = gson.fromJson(
sTotalString, GsonDataAnalysis. class );
for ( int i = 0 ; i < gda.getList().size(); i ++) {
System.out.print( "ID號:" + gda.getList().get(i).getId() + " " );
System.out.print( "姓 名:" + gda.getList().get(i).getName() + " " );
System.out.println( "年 齡:" + gda.getList().get(i).getAge());
}
}
}
|
註:在使用Gson類的時候在工程中要添加Gson.jar包。