Springboot序列化和反序列化LocalDateTime
java哥
阅读:1035
2021-04-01 11:11:34
评论:0
一、注解方式
1.出参
@Data
@ApiModel
public class ResVO {
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",shape=JsonFormat.Shape.STRING)
@ApiModelProperty(name="dateTime",value="日期",example="2020-03-17 12:07:00")
private LocalDateTime dateTime;
}
2.入参
a.Date类型
@Data
@ApiModel(description="入参对象",value="rucna")
public class ReqVO {
@JsonFormat(pattern="yyyy-MM-dd")
@ApiModelProperty(name="dateTime",required=true,example="2020-12-10")
private Date dateTime;
}
b.LocalDateTime类型
public class DateDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
if (StringUtils.isBlank(jsonParser.getText()))
return null;
LocalDate localDate = LocalDate.parse(jsonParser.getText(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
return LocalDateTime.of(localDate, LocalTime.MIN);
}
}
@Data
@ApiModel(description="入参对象",value="rucna")
public class ReqVO {
@JsonDeserialize(using = DateDeserializer.class)
@ApiModelProperty(name="dateTime",required=true,example="2020-12-10")
private LocalDateTime dateTime;
}
3.入参
4.出参
二、全局方式
1.配置类
@Configuration
public class LocalDateTimeConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizeLocalDateTimeFormat(@Value("${spring.jackson.date-format}") String pattern) {
return jacksonObjectMapperBuilder -> {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(formatter);
LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(formatter);
jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, serializer);
jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, deserializer);
};
}
}
2.测试demo
@PostMapping("/testDate")
@ApiOperation(value="测试时间格式化", notes="")
public ResVo login2(@RequestBody ReqVo req)
{
System.out.println(JSONObject.toJSONString(req));
LocalDateTime date = req.getDate();
LocalDateTime plusHours = date.plusHours(2);
ResVo resVo = new ResVo();
resVo.setDate(plusHours);
resVo.setId(18);
return resVo;
}
@ApiModel
@Data
public class ReqVo {
@ApiModelProperty(name="date",value="时间")
private LocalDateTime date;
@ApiModelProperty(name="id",value="序号")
private Integer id;
}
3.入参
4.出参
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。