Jackson 中SimpleModule的作用
SimpleModule中的作用可以用于json数据类型的转换。例如我们想将前端传过的时间类型yyyy-mm-dd的类型转成localdataTime。我们可以利用SimpleModule做一个全局的配置,正对时间类型的数据。前端只需要给我们yyyy-mm-dd ,后端根据自定义 SimpleModule 进行转换。
public JavaTimeModule() {
super(PackageVersion.VERSION);
//序列化,
this.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
this.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
this.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
//反序列化
this.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
this.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
this.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
}
我们可以定义其的序列化和反序列化模式。我们也可以转其他的类型例如Long类型的转成string类型。
接下来我们定义两个接口测试一下看看。如下:
package com.medusa.gruul.account.controller;
import com.alibaba.fastjson.JSONObject;
import com.medusa.gruul.account.model.User;
import jdk.nashorn.internal.ir.ReturnNode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.Objects;
@RestController
@RequestMapping("/jackson")
public class JacksonController {
@GetMapping("/test")
public User jackSonTest() {
User user = new User();
user.setId("1");
user.setUserName("userName");
user.setPassword("123456");
user.setCreateTime(LocalDateTime.now());
user.setUpdateTime(LocalDateTime.now());
return user;
}
@PostMapping("/test01")
public void jackSonTest01(@RequestBody User user) {
System.out.println(JSONObject.toJSON(user));
}
}
一个是获取 user,一个是接受user。调用第一个接口测试发现:
时间类型的已经成功转换成为了yyyy-mm-dd的类型。第二个接口返回
可以看到成功的将yyyy-mm-dd类型的时间格式转换成为了我们需要的LocalDateTime类型。