1.添加依赖
com.google.code.gson
gson
org.projectlombok
lombok
toJson:用于序列化,对象转Json数据 fromJson:用于反序列化,把Json数据转成对象
示例代码如下:
import lombok.*;
/**
* @author qinxun
* @date 2023-05-30
* @Descripion: 学生实体类
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
private Long termId;
private Long classId;
private Long studentId;
private String name;
}
import com.example.quartzdemo.entity.Student;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion: Gson测试
*/
@SpringBootTest
public class GsonTest {
@Test
void test1() {
Student student = new Student(1L, 2L, 2L, "张三");
Gson gson = new Gson();
// 输出{"termId":1,"classId":2,"studentId":2,"name":"张三"}
System.out.println(gson.toJson(student));
String data = "{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"}";
Student studentData = gson.fromJson(data, Student.class);
// 输出Student(termId=2, classId=2, studentId=2, name=李四)
System.out.println(studentData);
}
}
1.添加依赖
com.alibaba
fastjson
1.2.83
JSON.toJSONString(obj):用于序列化对象,转成json数据。
JSON.parseObject(obj,class): 用于反序列化对象,转成数据对象。
JSON.parseArray():把 JSON 字符串转成集合
示例代码如下:
mport com.alibaba.fastjson.JSON;
import com.example.quartzdemo.entity.Student;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion: fastjson测试
*/
@SpringBootTest
public class FastJsonTest {
@Test
void test1() {
Student student = new Student(1L, 2L, 2L, "张三");
String json = JSON.toJSONString(student);
// 输出{"classId":2,"name":"张三","studentId":2,"termId":1}
System.out.println(json);
String data = "{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"}";
Student student1 = JSON.parseObject(data, Student.class);
// 输出Student(termId=2, classId=2, studentId=2, name=李四)
System.out.println(student1);
String arrStr = "[{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"},{\"termId\":1,\"classId\":2,\"studentId\":2,\"name\":\"张三\"}]";
List studentList = JSON.parseArray(arrStr, Student.class);
// 输出[Student(termId=2, classId=2, studentId=2, name=李四), Student(termId=1, classId=2, studentId=2, name=张三)]
System.out.println(studentList);
}
}
2.使用注解
有时候,你的 JSON 字符串中的 key 可能与 Java 对象中的字段不匹配,比如大小写;有时候,你需要指定一些字段序列化但不反序列化;有时候,你需要日期字段显示成指定的格式。
我们只需要在对应的字段上加上 @JSONField
注解就可以了。
name 用来指定字段的名称,format 用来指定日期格式,serialize 和 deserialize 用来指定是否序列化和反序列化。
public @interface JSONField {
String name() default "";
String format() default "";
boolean serialize() default true;
boolean deserialize() default true;
}
import com.alibaba.fastjson.annotation.JSONField;
import lombok.*;
import java.util.Date;
/**
* @author qinxun
* @date 2023-05-30
* @Descripion: 学生实体类
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
private Long termId;
private Long classId;
@JSONField(serialize = false, deserialize = true)
private Long studentId;
private String name;
@JSONField(format = "yyyy年MM月dd日")
private Date birthday;
}
我们设置studentId不支持序列化,但是支持反序列化。
测试示例代码如下:
import com.alibaba.fastjson.JSON;
import com.example.quartzdemo.entity.Student;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.List;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion: fastjson测试
*/
@SpringBootTest
public class FastJsonTest {
@Test
void test1() {
Student student = new Student(1L, 2L, 2L, "张三", new Date());
String json = JSON.toJSONString(student);
// 输出{"birthday":"2023年06月09日","classId":2,"name":"张三","termId":1}
System.out.println(json);
String data = "{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"}";
Student student1 = JSON.parseObject(data, Student.class);
// 输出Student(termId=2, classId=2, studentId=2, name=李四, birthday=null)
System.out.println(student1);
String arrStr = "[{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"},{\"termId\":1,\"classId\":2,\"studentId\":2,\"name\":\"张三\"}]";
List studentList = JSON.parseArray(arrStr, Student.class);
// 输出[Student(termId=2, classId=2, studentId=2, name=李四, birthday=null), Student(termId=1, classId=2, studentId=2, name=张三, birthday=null)]
System.out.println(studentList);
}
}
执行结果:
{"birthday":"2023年06月09日","classId":2,"name":"张三","termId":1}
Student(termId=2, classId=2, studentId=2, name=李四, birthday=null)
[Student(termId=2, classId=2, studentId=2, name=李四, birthday=null), Student(termId=1, classId=2, studentId=2, name=张三, birthday=null)]
我们发现studentId没有被序列化成json数据。birthday生成了自定义的数据格式。
1.添加依赖
org.springframework.boot
spring-boot-starter-web
我们添加默认的web依赖就自动的添加了Jackson的依赖。
2.序列化
writeValueAsString(Object value)
方法,将对象存储成字符串writeValueAsBytes(Object value)
方法,将对象存储成字节数组writeValue(File resultFile, Object value)
方法,将对象存储成文件示例代码如下:
import lombok.*;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion:
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Writer {
private String name;
private int age;
}
import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion:
*/
@SpringBootTest
public class JacksonTest {
@Test
void test1() throws JsonProcessingException {
Writer writer = new Writer("qx", 25);
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(writer);
System.out.println(jsonStr);
}
}
执行结果:
{
"name" : "qx",
"age" : 25
}
不是所有的字段都支持序列化和反序列化,需要符合以下规则:
3.反序列化
readValue(String content, Class valueType)
方法,将字符串反序列化为 Java 对象readValue(byte[] src, Class valueType)
方法,将字节数组反序列化为 Java 对象readValue(File src, Class valueType)
方法,将文件反序列化为 Java 对象示例代码如下:
import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion:
*/
@SpringBootTest
public class JacksonTest {
@Test
void test1() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\n" +
" \"name\" : \"qx\",\n" +
" \"age\" : 18\n" +
"}";
Writer writer = mapper.readValue(jsonString, Writer.class);
// 输出Writer(name=qx, age=18)
System.out.println(writer);
}
}
借助 TypeReference 可以将 JSON 字符串数组转成泛型 List
示例代码如下:
import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion:
*/
@SpringBootTest
public class JacksonTest {
@Test
void test1() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String json = "[{ \"name\" : \"张三\", \"age\" : 18 }, { \"name\" : \"李四\", \"age\" : 19 }]";
List writerList = mapper.readValue(json, new TypeReference>() {
});
// 输出[Writer(name=张三, age=18), Writer(name=李四, age=19)]
System.out.println(writerList);
}
}
4.日期格式
我们使用@JsonFormat注解实现自定义的日期格式
示例代码如下:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import java.util.Date;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion:
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Writer {
private String name;
private int age;
@JsonFormat(pattern = "yyyy年MM月dd日")
private Date birthday;
}
import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion:
*/
@SpringBootTest
public class JacksonTest {
@Test
void test1() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Writer writer = new Writer("张三", 25, new Date());
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(writer);
System.out.println(json);
}
}
程序执行:
{
"name" : "张三",
"age" : 25,
"birthday" : "2023年06月09日"
}
5.字段过滤
在将 Java 对象序列化为 JSON 时,可能有些字段需要过滤,不显示在 JSON 中,我们使用@JsonIgnore 用于过滤单个字段。
示例代码如下:
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import java.util.Date;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion:
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Writer {
private String name;
@JsonIgnore
private int age;
@JsonFormat(pattern = "yyyy年MM月dd日")
private Date birthday;
}
import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
/**
* @author qinxun
* @date 2023-06-09
* @Descripion:
*/
@SpringBootTest
public class JacksonTest {
@Test
void test1() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Writer writer = new Writer("张三", 25, new Date());
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(writer);
System.out.println(json);
}
}
程序执行结果
{
"name" : "张三",
"birthday" : "2023年06月09日"
}