Gson Demo

原文:http://www.cnblogs.com/chenlhuaf/archive/2011/05/01/gson_test.html

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;

public class Person {

    private String name;
    private int age;

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return name + ":" + age;
    }

    public static void main(String[] args) {
        Gson gson = new Gson();
        List<Person> persons = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Person p = new Person();
            p.setName("name" + i);
            p.setAge(i * 5);
            persons.add(p);
        }
        String str = gson.toJson(persons);
        System.out.println(str);
        String gstr = "{\"name\":\"name0\",\"age\":0}";
        //String gstr = "[{\"name\":\"Name\",\"age\":99}]";
        Person n = gson.fromJson(gstr, Person.class);
        System.out.println(n.toString());


        List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>() {
        }.getType());
        for (int i = 0; i < ps.size(); i++) {
            Person p = ps.get(i);
            System.out.println(p.toString());
        }
    }
}
posted @ 2012-09-12 13:51  Leo Forest  阅读(578)  评论(0编辑  收藏  举报