Gson用法

首先先展示很多人要找的关键代码

List<Person> list2 = new Gson().fromJson(json,new TypeToken<List<Person>>(){}.getType());

很多人看完这行代码就不用往下看了。

 

首先定义一个Person类

 1 public class Person {
 2 
 3     private String name;
 4     private int age;
 5 
 6     public String getName() {
 7         return name;
 8     }
 9     public void setName(String name) {
10         this.name = name;
11     }
12 
13     public int getAge() {
14         return age;
15     }
16     public void setAge(int age) {
17         this.age = age;
18     }
19 }

接下来是使用gson。

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 import com.google.gson.Gson;
 5 import com.google.gson.reflect.TypeToken;
 6 
 7 public class Test {
 8 
 9     public static void main(String[] args) {
10         List<Person> list = new ArrayList<Person>();
11         Person p = new Person();
12         for (int i = 0; i < 4; i++) {
13             p.setAge(22);
14             p.setName("aa");
15             list.add(p);
16         }
17         String json = new Gson().toJson(list);
18         System.out.println(json);
19 
20         List<Person> list2 = new Gson().fromJson(json,new TypeToken<List<Person>>(){}.getType());
21         for (int i = 0; i < list2.size(); i++) {
22             Person p2 = list2.get(i);
23             System.out.println(p2.getName() + ":" + p2.getAge());
24         }
25     }
26 }

 

posted @ 2015-07-17 01:01  flyfly121  阅读(187)  评论(0编辑  收藏  举报