package com.jsonTest.test;
import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;
import com.jsonTest.entity.Student;
import com.jsonTest.entity.StudentListType;
import com.jsonTest.entity.StudentMapType;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GsonTest {
/**
* javabean与json中的关系
*/
@Test
public void test1(){
Student student=new Student("1","web");
Gson gson=new Gson();
String toJson = gson.toJson(student);
System.out.println(student);
System.out.println("普通对象变成json"+toJson);
/**
* Student(id=1, name=web)
* 普通对象变成json{"id":"1","name":"web"}
*/
/**
* 将当前的json转化成Javabean
*/
Student student1 = gson.fromJson(toJson, Student.class);
System.out.println(student1);
}
@Test
public void TestList(){
List<Student> studentList=new ArrayList<>();
studentList.add(new Student("2","小路卡"));
studentList.add(new Student("3","小卢卡"));
Gson gson=new Gson();
//list转成json
String jsonList = gson.toJson(studentList);
System.out.println("lIST"+studentList);
System.out.println("list-->JSON"+jsonList);
/**
* lIST[Student(id=2, name=小路卡), Student(id=3, name=小卢卡)]
* list-->JSON[{"id":"2","name":"小路卡"},{"id":"3","name":"小卢卡"}]
*/
// jsonList转成对象或者List
List list = gson.fromJson(jsonList, List.class);
System.out.println(list);//这个会发生类型转化异常
/**
* lIST转成对象需要一个type做标准
*/
List list1 = gson.fromJson(jsonList, new StudentListType().getType());
System.out.println(list1);
}
@Test
public void TestMap(){
Map<String,Student> studentMap=new HashMap();
studentMap.put("1",new Student("4","lucas"));
studentMap.put("2",new Student("5","xiaoLucas"));
Gson gson=new Gson();
//将map转成json
String toJsonMap = gson.toJson(studentMap);
System.out.println("jsonMap"+toJsonMap);
/**
* jsonMap{"1":{"id":"4","name":"lucas"},"2":{"id":"5","name":"xiaoLucas"}}
*/
/**
* 将map转成一个个对象
*/
Map<String,Student> student = gson.fromJson(toJsonMap, new StudentMapType().getType());
System.out.println(student);
Student student1 = student.get(1);
System.out.println(student1);
/**
* 在每次转换的时候都会出现新增的Type类,所以我们可以使用匿名内部类的方式
*/
}
@Test
public void TestMap2(){
Map<String,Student> studentMap=new HashMap();
studentMap.put("1",new Student("4","lucas"));
studentMap.put("2",new Student("5","xiaoLucas"));
Gson gson=new Gson();
//将map转成json
String toJsonMap = gson.toJson(studentMap);
System.out.println("jsonMap"+toJsonMap);
/**
* jsonMap{"1":{"id":"4","name":"lucas"},"2":{"id":"5","name":"xiaoLucas"}}
*/
/**
* 将map转成一个个对象
*/
Map<String,Student> student = gson.fromJson(toJsonMap,new TypeToken<Map<String,Student>>(){}.getType());
System.out.println(student);
Student student1 = student.get("1");
System.out.println(student1);
/**
* jsonMap{"1":{"id":"4","name":"lucas"},"2":{"id":"5","name":"xiaoLucas"}}
* {1=Student(id=4, name=lucas), 2=Student(id=5, name=xiaoLucas)}
* Student(id=4, name=lucas)
*/
/**
* 在每次转换的时候都会出现新增的Type类,所以我们可以使用匿名内部类的方式
*/
}
}
评论