一、反序列化—注解方式
1、localDateTime
若前端传参(Json格式)给后台,其中有一个参数是要用localDateTime接收,即需要反序列化为localDateTime类型。可使用注解的方式完成该过程。
后台创建一个query类来接收前端传过来的参数,在对应反序列化的字段上添加
com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime startTime;
2、List
若前端传过来的数组类型(String),后端在query类中对应的字段加上反序列化注解
@JsonDeserialize(using = CommaStringAsListDeserializer.class)
private List<String> name;
CommaStringAsListDeserializer.class
public class CommaStringAsListDeserializer extends JsonDeserializer<List<String>> {
@Override
public List<String> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
String s = jsonParser.getValueAsString();
if (!StringUtils.isEmpty(s)) {
String[] ids = s.split(",");
return Arrays.stream(ids).filter(x -> !x.isEmpty()).collect(Collectors.toList());
}
return Collections.emptyList();
}
}
二、序列化—注解的方式
后端创建一个对象接收数据库查询结果(该对象主要是用来与前端交互:VO),对于LocalDateTime等需要添加序列化注解
//LocalDateTime
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime startTime;
三、LocalDateTime
将LocalDateTime转化为LocalDate
LocalDateTime time = new LocalDateTime("2021-11-11 12:00:00");
time.toLocalDate();//2021-11-11
计算两个LocalDate类型的时间差
private LocalDate date1;
private LocalDate date2;
Long l1 = date1.toEppchDay();
Long l2 = date2.toEpochDay();
if(l1 > l2){
Long l = l1 - l2;
}else{
Long l = l2 - l1;
}
计算两个LocalDateTime类型时间差
private LocalDateTime date1;
private LocalDateTime date2;
//将LocalDateTime转化为LocalDate
Long l1 = date1.toLocalDate().toEpochDay();
Long l2 = date2.toLocalDate().toEpochDay();
//计算两个日期间的时间差(天)
if(l1 > l2){
Long l = l1 - l2;
}else{
Long l = l2 - l1;
}
四、关于PO、VO、BO、以及Query
- PO:即对象实体类enity(POJO),如学生实体类:Student、教师实体类:Teacher
- VO:即视图实体类(View Object),是为了页面取值方便,将数据封装成一个对象。VO主要用于逻辑层与应用层之间的数据封装。简单的说,就是前端要什么数据,我们就封装在VO中,传给前端。
- BO:业务对象(Business Object),业务对象主要作用是把业务逻辑封装为一个对象。这个对象可以包括一个或多个其它的对象。
- Query:查询对象,将前端发送的参数字段进行一次封装,通过Query对象接收前端传过来的参数值(涉及反序列化)。