1 模块的gradle文件导入依赖
implementation 'com.google.code.gson:gson:2.8.6'
2 代码
说明:集合的反序列化 需要用TypeToken来获取type
package com.example.myjson;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Test1 {
@Test
public void jsonTransfer(){
//1数组的序列化与反序列化
Student[] students = new Student[3];
students[0] = new Student("胡萝",12);
students[1] = new Student("西瓜",8);
students[2] = new Student("西红柿",9);
//序列化
String json= new Gson().toJson(students);
System.out.println("序列化:"+json);
//反序列化
Student[] student = new Gson().fromJson(json,Student[].class);
System.out.println("反序列化:"+student[0]);
System.out.println("----------------------------------------------------");
//2集合的序列化与反序列化
//2.1 List
List<Student> list = new ArrayList<>();
list.add(new Student("茉莉",12));
list.add(new Student("绿茶",15));
list.add(new Student("玫瑰",13));
//序列化
String json2= new Gson().toJson(list);
System.out.println("序列化:"+json2);
//反序列化
Type type =new TypeToken<List<Student>>(){}.getType();
List<Student> list2 = new Gson().fromJson(json2,type);
System.out.println("反序列化:"+list2.get(0));
System.out.println("----------------------------------------------------");
//2.2 Map
Map<String,Student> maps = new HashMap<>();
maps.put("key0",new Student("陈皮",11));
maps.put("key1",new Student("白果",8));
maps.put("key2",new Student("甘草",15));
//序列化
String json3= new Gson().toJson(maps);
System.out.println("序列化:"+json3);
//反序列化
Type type3 =new TypeToken<Map<String,Student>>(){}.getType();
Map<String,Student> maps3 = new Gson().fromJson(json3,type3);
System.out.println("反序列化:"+maps3.get("key0"));
System.out.println("----------------------------------------------------");
//2.3 Set
Set<Student> set = new HashSet<>();
set.add(new Student("蜂蜜",10));
set.add(new Student("枇杷膏",9));
set.add(new Student("米汤",8));
//序列化
String json4= new Gson().toJson(set);
System.out.println("序列化:"+json4);
//反序列化
Type type4 =new TypeToken<Set<Student>>(){}.getType();
Set<Student> set4 = new Gson().fromJson(json4,type4);
Iterator<Student> iterator = set4.iterator();
while(iterator.hasNext()){
System.out.println("反序列化:"+iterator.next());
}
//备注:HashSet 完全可以用反序列List,因为两者序列化后的json数据一致
}
}
结果