JAVA使用Gson解析json数据,实例
封装类Attribute:
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:
public class GsonDataAnalysis { private List<Attribute> list; public List<Attribute> getList() { return list; } public void setList(List<Attribute> list) { this.list = list; } }
测试类Main方法:
/** * 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包。