今天群友问了个问题,关于 LocalDateTime 序列化的问题
这里记录下解决办法
1、添加依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.9</version>
</dependency>
2、添加配置
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class MvcConfig {
@Bean
public ObjectMapper initObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// localDateTime按照 "yyyy-MM-dd HH:mm:ss"的格式进行序列化、反序列化
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}
3、测试
1)创建实体类
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
@Data
public class User {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime localDateTime = LocalDateTime.now();
}
2)控制器,分别演示返回和接收参数
import com.example.demo.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
@RestController
public class DemoController {
/**
* 返回参数 序列化测试
* @return
* @throws Exception
*/
@GetMapping("/test")
public User test() throws Exception {
User user = new User();;
return user;
}
/**
* 入参测试 反序列化测试
* {
* "localDateTime": "2022-10-12 00:10:30"
* }
* @param user
* @return
* @throws Exception
*/
@PostMapping("/test2")
public User test(@RequestBody User user) throws Exception {
return user;
}
}
3)效果图
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏