可以把module理解为给ObjectMapper添加自定义的功能
Person 类
我们先看下面这个Person类,里面有个Date类型的属性,我们想写出时间的时候,写出来的样子是:yyyy-MM-dd HH:mm:ss。这里我们不用@JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”)(类似于有些类在源码里面,我们根本改不了它们),我们尝试用ObjectMapper来写。
@Data
public class Person {
private String name;
private Integer age;
private Date date;
public Person() {
}
public Person(String name, Integer age,Date date) {
this.name = name;
this.age = age;
this.date = date;
}
}
ObjectMapper测试1
发现jackson是能够正常写出时间,并且读取时间的。但是,这个时间戳并不具有可读性,不够直观。所以,下面尝试使用jackson的module来扩展功能
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Person person = new Person("zzhua", 19, new Date());
System.out.println(mapper.writeValueAsString(person));
Object o = mapper.readerFor(Person.class).readValue("{\"name\":\"zzhua\",\"age\":19,\"date\":1682518824158}");
System.out.println(o);
}
/*输出:
{"name":"zzhua","age":19,"date":1682518854568}
Person(name=zzhua, age=19, date=Wed Apr 26 22:20:24 CST 2023)
*/
ObjectMapper测试2
通过给mapper添加module,在module中可以为指定的类型添加序列化器和反序列化器,就可以实现相当于自定义序列化和反序列化的效果。module中除了这种功能之外,还有很多其它的功能
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Date.class, new DateJsonSerializer());
simpleModule.addDeserializer(Date.class, new DateJsonDeserializer());
mapper.registerModule(simpleModule);
Person person = new Person("zzhua", 19, new Date());
System.out.println(mapper.writeValueAsString(person));
Object o = mapper.readerFor(Person.class).readValue("{\"name\":\"zzhua\",\"age\":19,\"date\":\"2023-04-26 22:25:57\"}");
System.out.println(o);
}
/* 输出:
{"name":"zzhua","age":19,"date":"2023-04-26 22:26:14"}
Person(name=zzhua, age=19, date=Wed Apr 26 22:25:57 CST 2023)
*/
DateJsonSerializer
写一个Date类型的序列化器
public class DateJsonSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (value != null) {
String fmtDateStr = sdf.format(value);
gen.writeString(fmtDateStr);
}
}
}
DateJsonDeserializer
写一个Date类型的反序列化器
@Slf4j
public class DateJsonDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String valueStr = p.getValueAsString();
try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(valueStr);
} catch (ParseException e) {
log.error("解析时间错误");
}
return null;
}
}