欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA使用Gson解析json数据,实例

程序员文章站 2024-03-16 08:39:34
...
封装类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());
            }
        }
     
}