使用Gson 解析json

介绍一下是用Gson来解析json的方式。

Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。

直接上代码吧,代码里面有一些注释。参考了老罗的demo和lk_blog的博客。

 还是那句话,json传递过来,在一些环境下是直接解析然后做其他处理,有的时候要转换到一个java对象。

先上java对象。我直接放到一个文件里面了。

  1 package com.android.domain;
  2 
  3 import java.util.Date;
  4 
  5 public class Person {
  6 
  7     private String name;
  8     private int age;
  9     private String address;
 10     private Date birthDay;
 11 
 12     public String getName() {
 13         return name;
 14     }
 15 
 16     public Date getBirthDay() {
 17         return birthDay;
 18     }
 19 
 20     public void setBirthDay(Date birthDay) {
 21         this.birthDay = birthDay;
 22     }
 23 
 24     @Override
 25     public String toString() {
 26         return "Person [name=" + name + ", age=" + age + ", address=" + address
 27                 + ", birthDay=" + birthDay + "]";
 28     }
 29 
 30     public void setName(String name) {
 31         this.name = name;
 32     }
 33 
 34     public int getAge() {
 35         return age;
 36     }
 37 
 38     public void setAge(int age) {
 39         this.age = age;
 40     }
 41 
 42     public String getAddress() {
 43         return address;
 44     }
 45 
 46     public void setAddress(String address) {
 47         this.address = address;
 48     }
 49 
 50     public Person() {
 51         // TODO Auto-generated constructor stub
 52     }
 53 
 54 }
 55 
 56 
 57 package com.android.domain;
 58 
 59 public class Point {
 60     private int x;
 61     private int y;
 62 
 63     public Point(int x, int y) {
 64         this.x = x;
 65         this.y = y;
 66     }
 67 
 68     public int getX() {
 69         return x;
 70     }
 71 
 72     public void setX(int x) {
 73         this.x = x;
 74     }
 75 
 76     public int getY() {
 77         return y;
 78     }
 79 
 80     public void setY(int y) {
 81         this.y = y;
 82     }
 83 
 84     @Override
 85     public String toString() {
 86         return "Point [x=" + x + ", y=" + y + "]";
 87     }
 88 
 89 }
 90 
 91 package com.android.domain;
 92 
 93 import java.util.Date;
 94 
 95 import com.google.gson.annotations.Expose;
 96 import com.google.gson.annotations.SerializedName;
 97 
 98 public class Student {
 99     private int id;
100 
101     @Expose
102     private String name;
103 
104     @Expose
105     @SerializedName("bir")
106     private Date birthDay;
107 
108     public int getId() {
109         return id;
110     }
111 
112     public void setId(int id) {
113         this.id = id;
114     }
115 
116     public String getName() {
117         return name;
118     }
119 
120     public void setName(String name) {
121         this.name = name;
122     }
123 
124     public Date getBirthDay() {
125         return birthDay;
126     }
127 
128     public void setBirthDay(Date birthDay) {
129         this.birthDay = birthDay;
130     }
131 
132     @Override
133     public String toString() {
134         return "Student [birthDay=" + birthDay + ", id=" + id + ", name="
135                 + name + "]";
136     }
137 
138 }

 

接着就是执行类了。这里只是java的,跟android的差别不大。

  1 package com.android.mygson;
  2 
  3 import java.util.ArrayList;
  4 import java.util.Date;
  5 import java.util.HashMap;
  6 import java.util.LinkedHashMap;
  7 import java.util.List;
  8 import java.util.Map;
  9 
 10 import com.android.domain.Person;
 11 import com.android.domain.Point;
 12 import com.google.gson.Gson;
 13 import com.google.gson.reflect.TypeToken;
 14 
 15 public class GsonTools {
 16 
 17     public GsonTools() {
 18         // TODO Auto-generated constructor stub
 19     }
 20 
 21     public static String createGsonString(Object object) {
 22         Gson gson = new Gson();
 23         String gsonString = gson.toJson(object);
 24         return gsonString;
 25     }
 26 
 27     public static <T> T changeGsonToBean(String gsonString, Class<T> cls) {
 28         Gson gson = new Gson();
 29         T t = gson.fromJson(gsonString, cls);
 30         return t;
 31     }
 32 
 33     public static <T> List<T> changeGsonToList(String gsonString, Class<T> cls) {
 34         Gson gson = new Gson();
 35         List<T> list_person = gson.fromJson(gsonString,
 36                 new TypeToken<List<T>>() {
 37                 }.getType());
 38         return list_person;
 39     }
 40 
 41     public static List<Map<String, Object>> changeGsonToListMaps(String gsonString) {
 42         List<Map<String, Object>> list = null;
 43         Gson gson = new Gson();
 44         list = gson.fromJson(gsonString,
 45                 new TypeToken<List<Map<String, Object>>>() {
 46                 }.getType());
 47         return list;
 48     }
 49 
 50     //这个方法太水了,因为json本来就是类似与map。。。
 51     public static Map<String, Point> changeGsonToMap(String gsonString){
 52         Map <String,Point> map = null;
 53         Gson gson= new Gson();
 54         map=gson.fromJson(gsonString, new TypeToken<Map<String,Object>>(){}.getType());
 55         return map;
 56         
 57     }
 58     /**
 59      * @param args
 60      */
 61     public static void main(String[] args) {
 62         // TODO Auto-generated method stub
 63         
 64         
 65         
 66         Person person1= new Person();
 67         person1.setAge(1);  
 68         person1.setName("xx");  
 69         person1.setBirthDay(new Date());  
 70         
 71         // //////////////////////////////////////////////////////////  
 72         System.out.println("----------简单对象之间的转化-------------");  
 73         // 简单的bean转为json  
 74         String s1 = createGsonString(person1);  
 75         System.out.println("简单Bean转化为Json===" + s1);  
 76   
 77         // json转为简单Bean  
 78         Person person = changeGsonToBean(s1, Person.class);  
 79         System.out.println("Json转为简单Bean===" + person);      
 80         
 81         
 82         Person person2= new Person();
 83         person2.setAge(2);  
 84         person2.setName("xue");  
 85         person2.setBirthDay(new Date());  
 86         Person person3= new Person();
 87         person3.setAge(3);  
 88         person3.setName("yuan");  
 89         person3.setBirthDay(new Date());  
 90     
 91         
 92         List<Person> list= new ArrayList<Person>();
 93         list.add(person1);
 94         list.add(person2);
 95         list.add(person3);
 96         
 97         System.out.println("----------带泛型的List之间的转化-------------");  
 98         // 带泛型的list转化为json  
 99         String s2 = createGsonString(list);  
100         System.out.println("带泛型的list转化为json==" + s2);  
101         
102         List<Person> retList=changeGsonToList(s2, Person.class);
103         System.out.println("Json转为List===" + retList);      
104         
105         
106         Map<String,Point > map_point = new LinkedHashMap<String,Point >();// 使用LinkedHashMap将结果按先进先出顺序排列
107         map_point.put( "first",new Point(5, 6));
108         map_point.put( "second",new Point(8, 8));
109         
110         String s_map=createGsonString(map_point);
111         System.out.println("map转化为json==" + s_map); 
112         
113          Map<String,Point> map_point1 = changeGsonToMap(s_map);
114          System.out.println("json转化为map==" + s_map); 
115         
116         
117         List<Map<String, Object>> list_map = new ArrayList<Map<String, Object>>();
118         Map<String, Object> map = new HashMap<String, Object>();
119         map.put("name", "jack");
120         map.put("age", 23);
121         Map<String, Object> map2 = new HashMap<String, Object>();
122         map2.put("name", "rose");
123         map2.put("age", 24);
124         list_map.add(map);
125         list_map.add(map2);
126         String gsonString = createGsonString(list);
127         System.out.println(gsonString);
128         System.out.println("----------List嵌套map-------------");  
129         List<Map<String, Object>> list2 = changeGsonToListMaps(gsonString);
130         System.out.println(list2.toString());
131         
132         
133         
134     
135     }
136 
137 }

输出:

----------简单对象之间的转化-------------

简单Bean转化为Json==={"name":"xx","age":1,"birthDay":"Mar 27, 2014 6:31:09 PM"}

Json转为简单Bean===Person [name=xx, age=1, address=null, birthDay=Thu Mar 27 18:31:09 CST 2014]

----------带泛型的List之间的转化-------------

带泛型的list转化为json==[{"name":"xx","age":1,"birthDay":"Mar 27, 2014 6:31:09 PM"},{"name":"xue","age":2,"birthDay":"Mar 27, 2014 6:31:09 PM"},{"name":"yuan","age":3,"birthDay":"Mar 27, 2014 6:31:09 PM"}]

Json转为List===[{name=xx, age=1.0, birthDay=Mar 27, 2014 6:31:09 PM}, {name=xue, age=2.0, birthDay=Mar 27, 2014 6:31:09 PM}, {name=yuan, age=3.0, birthDay=Mar 27, 2014 6:31:09 PM}]

map转化为json=={"first":{"x":5,"y":6},"second":{"x":8,"y":8}}

json转化为map=={"first":{"x":5,"y":6},"second":{"x":8,"y":8}}

[{"name":"xx","age":1,"birthDay":"Mar 27, 2014 6:31:09 PM"},{"name":"xue","age":2,"birthDay":"Mar 27, 2014 6:31:09 PM"},{"name":"yuan","age":3,"birthDay":"Mar 27, 2014 6:31:09 PM"}]

----------List嵌套map-------------

[{name=xx, age=1.0, birthDay=Mar 27, 2014 6:31:09 PM}, {name=xue, age=2.0, birthDay=Mar 27, 2014 6:31:09 PM}, {name=yuan, age=3.0, birthDay=Mar 27, 2014 6:31:09 PM}]

 

 1 package com.android.mygson;
 2 import java.util.ArrayList;
 3 import java.util.Date;
 4 import java.util.List;
 5 
 6 import com.android.domain.Student;
 7 import com.google.gson.FieldNamingPolicy;
 8 import com.google.gson.Gson;
 9 import com.google.gson.GsonBuilder;
10 import com.google.gson.reflect.TypeToken;
11 
12 public class GsonTest2 {
13 
14     public static void main(String[] args) {
15         //注意这里的Gson的构建方式为GsonBuilder,区别于test1中的Gson gson = new Gson();
16         Gson gson = new GsonBuilder()
17         .excludeFieldsWithoutExposeAnnotation() //不导出实体中没有用@Expose注解的属性
18         .enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
19         .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式  
20         .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//会把字段首字母大写,注:对于实体上使用了@SerializedName注解的不会生效.
21         .setPrettyPrinting() //对json结果格式化.
22         .setVersion(1.0)    //有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化.
23                             //@Since(版本号)能完美地实现这个功能.还的字段可能,随着版本的升级而删除,那么
24                             //@Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.
25         .create();
26         
27         
28 
29         Student student1 = new Student();
30         student1.setId(1);
31         student1.setName("李坤");
32         student1.setBirthDay(new Date());
33 
34         // //////////////////////////////////////////////////////////
35         System.out.println("----------简单对象之间的转化-------------");
36         // 简单的bean转为json
37         String s1 = gson.toJson(student1);
38         System.out.println("简单Bean转化为Json===" + s1);
39 
40         // json转为简单Bean
41         Student student = gson.fromJson(s1, Student.class);
42         System.out.println("Json转为简单Bean===" + student);
43         // //////////////////////////////////////////////////////////
44 
45         Student student2 = new Student();
46         student2.setId(2);
47         student2.setName("曹贵生");
48         student2.setBirthDay(new Date());
49 
50         Student student3 = new Student();
51         student3.setId(3);
52         student3.setName("柳波");
53         student3.setBirthDay(new Date());
54 
55         List<Student> list = new ArrayList<Student>();
56         list.add(student1);
57         list.add(student2);
58         list.add(student3);
59 
60         System.out.println("----------带泛型的List之间的转化-------------");
61         // 带泛型的list转化为json
62         String s2 = gson.toJson(list);
63         System.out.println("带泛型的list转化为json==" + s2);
64 
65         // json转为带泛型的list
66         List<Student> retList = gson.fromJson(s2,
67                 new TypeToken<List<Student>>() {
68                 }.getType());
69         for (Student stu : retList) {
70             System.out.println(stu);
71         }
72         
73     }
74 }

输出:

----------简单对象之间的转化-------------

简单Bean转化为Json==={

  "Name": "李坤",

  "bir": "2014-03-27 18:32:20:301"

}

Json转为简单Bean===Student [birthDay=Thu Mar 27 18:32:20 CST 2014, id=0, name=李坤]

----------带泛型的List之间的转化-------------

带泛型的list转化为json==[

  {

    "Name": "李坤",

    "bir": "2014-03-27 18:32:20:301"

  },

  {

    "Name": "曹贵生",

    "bir": "2014-03-27 18:32:20:343"

  },

  {

    "Name": "柳波",

    "bir": "2014-03-27 18:32:20:343"

  }

]

Student [birthDay=Thu Mar 27 18:32:20 CST 2014, id=0, name=李坤]

Student [birthDay=Thu Mar 27 18:32:20 CST 2014, id=0, name=曹贵生]

Student [birthDay=Thu Mar 27 18:32:20 CST 2014, id=0, name=柳波]

 1 package com.android.mygson;
 2 
 3 import java.util.LinkedHashMap;
 4 import java.util.Map;
 5 
 6 import com.android.domain.Point;
 7 import com.google.gson.Gson;
 8 import com.google.gson.GsonBuilder;
 9 import com.google.gson.reflect.TypeToken;
10 
11 public class GsonTest3 {
12 
13     public static void main(String[] args) {
14         Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
15                 .create();
16 
17         Map<Point, String> map1 = new LinkedHashMap<Point, String>();// 使用LinkedHashMap将结果按先进先出顺序排列
18         map1.put(new Point(5, 6), "first");
19         map1.put(new Point(8, 8), "second");
20         String s = gson.toJson(map1);
21         System.out.println(s);
22 
23         Map<Point, String> retMap = gson.fromJson(s,
24                 new TypeToken<Map<Point, String>>() {
25                 }.getType());
26         for (Point p : retMap.keySet()) {
27             System.out.println("key:" + p + " values:" + retMap.get(p));
28         }
29         System.out.println(retMap);
30 
31         System.out.println("----------------------------------");
32         Map<String, Point> map2 = new LinkedHashMap<String, Point>();
33         map2.put("first", new Point(3, 4));
34         map2.put("second", new Point(5, 6));
35         String s2 = gson.toJson(map2);
36         System.out.println(s2);
37 
38         Map<String, Point> retMap2 = gson.fromJson(s2,
39                 new TypeToken<Map<String, Point>>() {
40                 }.getType());
41         for (String key : retMap2.keySet()) {
42             System.out.println("key:" + key + " values:" + retMap2.get(key));
43         }
44 
45     }
46 }

输出:

[[{"x":5,"y":6},"first"],[{"x":8,"y":8},"second"]]

key:Point [x=5, y=6] values:first

key:Point [x=8, y=8] values:second

{Point [x=5, y=6]=first, Point [x=8, y=8]=second}

----------------------------------

{"first":{"x":3,"y":4},"second":{"x":5,"y":6}}

key:first values:Point [x=3, y=4]

key:second values:Point [x=5, y=6]

使用Gson 解析json,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。