(五)Google Gson包的使用
1.简介
Gson包中,使用最多的是Gson类的toJson()和fromJson()方法:
①toJson():将java对象转化为json数据(一般为json格式的字符串) (序列化)
②fromJson():从json数据(json格式字符串)转为java对象 (反序列化)
也可以使用JsonObject和JsonArray类的无参构造函数创建实例,然后调用add()方法来构造json数据,用法与org.json包和json-lib包差不多,但却少了一些方法;这里使用Gson包还是推荐使用Gson类的toJson()和fromJson()方法。
Github上的原话:
Gson Goals:
- Provide simple
toJson()
andfromJson()
methods to convert Java objects to JSON and vice-versa - Allow pre-existing unmodifiable objects to be converted to and from JSON
- Extensive support of Java Generics
- Allow custom representations for objects
- Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
Github的地址:https://github.com/google/gson
各个版本的下载地址:http://www.mvnrepository.com/artifact/com.google.code.gson/gson例子:
1 package gson; 2 import com.google.gson.Gson; 3 public class Test { 4 public static void main(String[] args) { 5 Gson gson = new Gson(); 6 // 简单数据类型 转为 json 7 String intStr = gson.toJson(1); 8 String stringStr = gson.toJson("abcd"); 9 String longStr = gson.toJson(new Long(10)); 10 System.out.println(intStr); // int 11 System.out.println(stringStr); // String 12 System.out.println(longStr); // Long 13 // json 转为 简单数据类型 14 int id1 = gson.fromJson("1", int.class); 15 Integer id2 = gson.fromJson("1", Integer.class); 16 Boolean boolean1 = gson.fromJson("false", Boolean.class); 17 String str = gson.fromJson(""abc"", String.class); 18 System.out.println(id1); 19 System.out.println(id2); 20 System.out.println(boolean1); 21 System.out.println(str); 22 23 // java array 转为 json 24 String[] strings = { "abc", "def", "ghi" }; 25 int[][] intInt = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; 26 String stringStrs = gson.toJson(strings); // String数组转为json 27 String intIntStr = gson.toJson(intInt); // 多维数据转为json 28 System.out.println(stringStrs); 29 System.out.println(intIntStr); 30 //json 转为 java array 31 String[] strings2 = gson.fromJson(stringStrs, String[].class); 32 int[][] intInt2 = gson.fromJson(intIntStr, int[][].class); 33 for (int i = 0; i < strings2.length; i++) { //输出String[] 34 System.out.print(strings2[i] + " "); 35 } 36 System.out.println(); 37 for (int i = 0; i < intInt2.length; i++) { //输出int[][] 38 for (int j = 0; j < intInt2[i].length; j++) { 39 System.out.print(intInt2[i][j] + ","); 40 } 41 System.out.print(" "); 42 } 43 } 44 }
输出结果:
3.json与java集合、Map
例子:
1 package gson; 2 import java.lang.reflect.Type; 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 import com.google.gson.Gson; 8 import com.google.gson.reflect.TypeToken; 9 public class Test { 10 public static void main(String[] args) { 11 Gson gson = new Gson(); 12 // Map 转 json 13 Map<string object=""> map = new HashMap<string object="">(); 14 map.put("name", "JTZen9"); 15 map.put("age", 21); 16 map.put("sex", "male"); 17 String jsonMap = gson.toJson(map); 18 System.out.println(jsonMap); 19 // json 转 Map 20 Type type = new TypeToken<Map<string object="">>() {}.getType(); 21 Map<string object=""> map2 = gson.fromJson(jsonMap, type); 22 System.out.println(map2.get("name") + " " + map2.get("age") + " " + map2.get("sex")); 23 24 // java集合 转 json 25 List<object> nameList = new ArrayList</object><object>(); 26 nameList.add("JTZen9"); 27 nameList.add(map); 28 nameList.add("DSMGYH"); 29 String jsonNames = gson.toJson(nameList); 30 System.out.println(jsonNames); 31 // json 转 java集合 32 type = new TypeToken<List</object><object>>() {}.getType(); 33 List</object><object> list = gson.fromJson(jsonNames, type); 34 for (int i = 0; i < list.size(); i++) { 35 System.out.print(list.get(i) + " "); 36 } 37 } 38 }
输出结果:
1 package gson; 2 import com.google.gson.Gson; 3 public class Test { 4 public static void main(String[] args) { 5 Student student = new Student(); 6 student.setName("JTZen9"); 7 student.setAge(21); 8 student.setSex("male"); 9 Gson gson = new Gson(); 10 // java bean 转 json 11 String beanStr = gson.toJson(student); 12 System.out.println(beanStr); 13 // json 转 java bean 14 Student student2 = gson.fromJson(beanStr, Student.class); 15 System.out.println(student2.getName() + " " + student2.getAge() + " " + student2.getSex()); 16 17 // 转为json数据时,只会转换属性值的字段 18 Student stu = new Student(); 19 stu.setName("JTZen9"); 20 stu.setAge(21); 21 String test = gson.toJson(stu); 22 System.out.println(test); //没有sex字段 23 } 24 }
输出结果:
json-lib包中,JSONObject.fromObject()构造的json数据,全部的字段都包含,没有赋值的都为空;
Gson包的toJson()方法和org.json包的new JSONObject()方法,转换java bean为json数据时,只会转换有赋值的字段。
1 { 2 "roomname":[ 3 { 4 "PCnum":0, 5 "num":2, 6 "name":"biubiubiu", 7 "time":"十二月 18, 2015" 8 }, 9 { 10 "PCnum":0, 11 "num":1, 12 "name":"jtz", 13 "time":"十二月 19, 2015" 14 }, 15 { 16 "PCnum":0, 17 "num":1, 18 "name":"jtzeng", 19 "time":"十二月 19, 2015" 20 } 21 22 ] 23 }
使用JsonObject和JsonArray的配合来使用也是可以解析的,但是这样解析起来就比较麻烦,当json数据又多又复杂时候更是麻烦,所以这里有一种简单的方法,首先定义一个对应json数据字段的java类:
1 package gson; 2 import java.util.List; 3 public class JsonBean { 4 public List<roomdata> roomname; 5 public class RoomData { 6 public int PCnum; 7 public int num; 8 public String name; 9 public String time; 10 } 11 }
然后,测试如下:
1 package gson; 2 import java.lang.reflect.Type; 3 import com.google.gson.Gson; 4 import com.google.gson.reflect.TypeToken; 5 public class Test { 6 public static void main(String[] args) { 7 //要解析json数据 8 String json = "{'roomname':[{'PCnum':0,'num':2,'name':'biubiubiu','time':'Dec 22, 2015'}," 9 + "{'PCnum':0,'num':1,'name':'jtz','time':'Dec 18, 2015'}," 10 + "{'PCnum':0,'num':0,'name':'JTZen9','time':'Dec 22, 2015'}]}"; 11 Gson gson = new Gson(); 12 Type type = new TypeToken<jsonbean>(){}.getType(); 13 JsonBean jsonBean = gson.fromJson(json, type); 14 System.out.println(jsonBean.roomname.size()); 15 for (int i = 0; i < jsonBean.roomname.size(); i++) { 16 System.out.println(jsonBean.roomname.get(i).name + " 、 " 17 + jsonBean.roomname.get(i).PCnum + " 、 " 18 + jsonBean.roomname.get(i).num + " 、 " 19 + jsonBean.roomname.get(i).time); 20 } 21 } 22 }
输出的结果如下:
需要注意的是:定义的类中,属性字段名必须跟json数据的key字段名一样。
org.json包、json-lib包、Gson包,终于搞清楚了些,做课程作业时糊里糊涂的。相比之下,感觉Gson挺好用的,往后深入探究探究Gson。