json序列化和反序列化

  |  

安装包

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.15.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.15.3</version>
</dependency>

使用

序列化

1
2
3
4
5
Student student = new Student();
student.setName("张三");
student.setAge(10);
String jsonString = JsonUtil.toJSONString(student);
System.out.println(jsonString);

反序列化

1
2
3
4
5
6
7
8
9
10
11
12
String s = "{\"name\":\"张三\",\"age\":10}";
// 第一种
Student parse = JsonUtil.parse(s, Student.class);
System.out.println(parse);
// 第二种
Student parse1 = JsonUtil.parse(s, new TypeReference<Student>() {
});
System.out.println(parse1);
// 第三种
JavaType javaType = JsonUtil.getCollectionType(Student.class);
Object parse2 = JsonUtil.parse(s, javaType);
System.out.println(parse2);

代码示例

文章目录
  1. 1. 安装包
  2. 2. 使用
    1. 2.1. 序列化
    2. 2.2. 反序列化