首先注入Gson的依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
新建一个实体类Student
@Data
public class Student {
private Integer id;
private String name;
private String sex;
}
建立三个student的测试对象
Student student1 = new Student();
student1.setId(1);
student1.setName("Sam");
student1.setSex("male");
Student student2 = new Student();
student2.setId(2);
student2.setName("Tom");
student2.setSex("male");
Student student3 = new Student();
student3.setId(3);
student3.setName("luna");
student3.setSex("female");
(1)javabean转换为json:
public static String javabeanToJson(Student student){
Gson gson = new Gson();
String json = gson.toJson(student);
return json;
}
结果:
(2)将对象数组转化为json
public static String listToJson(List<Student> students){
Gson gson = new Gson();
String json = gson.toJson(students);
return json;
}
结果:
(3)map转化为json
public static String mapToJson(Map<String, Student> map) {
Gson gson = new Gson();
String json = gson.toJson(map);
return json;
}
结果:
(4)json转换为javabean
public static void jsonToJavabean(String json) {
Gson gson = new Gson();
Student student = gson.fromJson(json, Student.class);
System.out.println(student.toString());
}
结果:
(5)json转换为list
public static void jsonToList(String json) {
Gson gson = new Gson();
List<Student> students = gson.fromJson(json, new TypeToken<List<Student>>() {
}.getType());
for (Student student : students) {
System.out.println(student);
}
}
结果:
(6)json转换为map
public static void jsonToMap(String json) {
Gson gson = new Gson();
Map<String, Student> maps = gson.fromJson(json, new TypeToken<Map<String, Student>>() {
}.getType());
for (Map.Entry<String, Student> map : maps.entrySet()) {
System.out.println("key: " + map.getKey() + " value: " + map.getValue());
}
结果: