Gson简要使用笔记
Gson介绍:
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。
常用的2个方法:
Gson.toJson(Object src) --将对象进行json序列化
Gson.fromJson(String json,Class<T>) --将json字符串反序列化成对象
实体类:
1 package com.tuzi.gson.domain; 2 3 public class Student { 4 5 private int id; 6 private String name; 7 private int age; 8 9 public Student(int id, String name, int age) { 10 super(); 11 this.id = id; 12 this.name = name; 13 this.age = age; 14 } 15 16 public int getId() { 17 return id; 18 } 19 20 public void setId(int id) { 21 this.id = id; 22 } 23 24 public String getName() { 25 return name; 26 } 27 28 public void setName(String name) { 29 this.name = name; 30 } 31 32 public int getAge() { 33 return age; 34 } 35 36 public void setAge(int age) { 37 this.age = age; 38 } 39 40 @Override 41 public String toString() { 42 return "Student [age=" + age + ", id=" + id + ", name=" + name + "]"; 43 } 44 45 }
测试类:
1 package com.tuzi.gson.test; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 8 import com.google.gson.Gson; 9 import com.google.gson.reflect.TypeToken; 10 import com.tuzi.gson.domain.Student; 11 12 public class GsonTest { 13 14 public static void main(String[] args) { 15 16 //普通对象转换成json 17 Student student1=new Student(1, "tuzi", 22); 18 Gson gson=new Gson();//实例化一个Gson对象 19 String info1=gson.toJson(student1); 20 System.out.println("普通对象转换成json:"+info1); 21 22 //json反序列化(info1) 23 Student student2=gson.fromJson(info1, Student.class); 24 System.out.println("json字符串反序列化:"+student2.toString()); 25 System.out.println(); 26 27 28 29 //list集合(Student)对象转换成json 30 List<Student> list=new ArrayList<Student>(); 31 Student student3=new Student(3, "xiaoming", 22); 32 Student student4=new Student(4, "xiaofang", 22); 33 list.add(student3); 34 list.add(student4); 35 String info2=gson.toJson(list); 36 System.out.println("list集合(Student)对象转换成json:"+info2); 37 38 //json反序列化(info2) 39 List<Student> students=gson.fromJson(info2,new TypeToken<List<Student>>(){}.getType());//TypeToken是Google提供的一个解析Json数据的类库中一个类(任意类型) 40 System.out.println("json字符串反序列化:"+students.toString()); 41 System.out.println(); 42 43 44 //list集合(Map)对象转换成json 45 List<Map<String,Object>> list2=new ArrayList<Map<String,Object>>(); 46 Map<String,Object> map1=new HashMap<String, Object>(); 47 map1.put("id", 5); 48 map1.put("name", "小白"); 49 map1.put("age", 11); 50 51 Map<String,Object> map2=new HashMap<String, Object>(); 52 map2.put("id", 5); 53 map2.put("name", "小黑"); 54 map2.put("age", 13); 55 56 list2.add(map1); 57 list2.add(map2); 58 59 String info3=gson.toJson(list2); 60 System.out.println("list集合(Map)对象转换成json:"+info3.toString()); 61 62 //json反序列化(info2) 63 List<Map<String,Object>> list4=gson.fromJson(info3, new TypeToken<List<Map<String,Object>>>(){}.getType()); 64 System.out.println("json字符串反序列化:"+list4.toString()); 65 66 } 67 68 69 }
运行效果: