Gson 的使用
对象和 json 字符串的相互转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.itguigu.demo;
import org.junit.jupiter.api.Test;
import com.google.gson.Gson; import com.itguigu.bean.Student;
public class Demo { @Test public void testJsonStrObject() { Gson gson = new Gson(); Student student = new Student("zhangsan", 20); String json = gson.toJson(student); System.out.println(json); Student student2 = gson.fromJson(json, Student.class); System.out.println(student2); } }
|
带泛型的 List。因为有了泛型,所以我们在使用 fromJson 的时候就不能使用上面的那种方式了,而是要使用 TypeToke,将类型传递进去,然后通过 getType 获取类型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @Test public void testJsonStrList() { ArrayList<Student> students = new ArrayList<>(); students.add(new Student("lisi", 24)); students.add(new Student("wangwu", 88)); students.add(new Student("zhaoliu", 99)); Gson gson = new Gson(); String json = gson.toJson(students); System.out.println(json); ArrayList<Student> students2 = gson.fromJson(json, new TypeToken<ArrayList<Student>>() {}.getType()); System.out.println(students2.get(0)); System.out.println(students2.get(0).getName()); }
|
带泛型的 Map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Test public void testJsonStrMap() { HashMap<String, Student> map = new HashMap<>(); map.put("zhangsan", new Student("zhangsan", 99)); map.put("lisi", new Student("lisi", 44)); Gson gson = new Gson(); String json = gson.toJson(map); System.out.println(json); HashMap<String, Student> map2 = gson.fromJson(json, new TypeToken<HashMap<String, Student>>() {}.getType()); System.out.println(map2); System.out.println(map2.get("lisi")); System.out.println(map2.get("lisi").getAge()); }
|