There are often data processed in the request time format and response time format in the project. Here is a summary for your convenience. In addition to Date, other types can also extend their own serialization rules.
1. Return to install and change: JsonSerializer
The custom return time format is a timestamp Long or a string: yyyy-MM-dd HH:mm:ss
Annotate the corresponding entity class field: @JsonSerialize(using = DateJsonSerialize.class)
/**
* 时间处理: 返回时间戳
* <P> 字段上添加 @JsonSerialize(using = DateJsonSerialize.class) 注解 </P>
* @author wangsong
* @mail [email protected]
* @date 2020/11/21 0021 14:19
* @version 1.0.0
*/
public class DateJsonSerialize extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value != null) {
// value 为时间时,返回时间戳,字段上添加 @JsonSerialize(using = DateJsonSerialize.class) 注解
if (value.getClass().isAssignableFrom(Date.class)) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// String format = sdf.format((Date) value);
// gen.writeString(format);
String time = ((Date) value).getTime() + "";
gen.writeString(time);
}
}
}
}
Two, receive conversion Deserialize
The custom receiving time format is a timestamp Long or a string: yyyy-MM-dd HH:mm:ss is converted to entity type corresponding data
Add a comment on the corresponding entity class field or set method: @JsonDeserialize(using = DateJsonDeserialize.class)
public class DateJsonDeserialize extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
String text = p.getText();
if(StringUtils.isBlank(text)){
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(text);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}