您可以为您的自定义日期格式创建一个 Serializaer/Deserializer。
对于解串器:
public class JsonDateDeserializer extends JsonDeserializer<Date> {
private static final SimpleDateFormat dateFormat;
static {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
dateFormat.setTimeZone(SimpleTimeZone.getTimeZone("UTC"));
}
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException {
String date = jsonparser.getText();
if (date != null && !"".equals(date)) {
try {
return dateFormat.parse(date);
} catch (ParseException e) {
throw new JsonParseException(jsonparser, e.getMessage());
}
}
return null;
}
}
对于序列化器:
public class JsonDateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat dateFormat;
static {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
dateFormat.setTimeZone(SimpleTimeZone.getTimeZone("UTC"));
}
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
在你的 POJO 中:
@Data
public class Person implements Serializable {
private static final long serialVersionUID = -8041031461422721556L;
private Long id;
private String name;
@JsonSerialize(using = JsonDateSerializer.class)
@JsonDeserialize(using = JsonDateDeserializer.class)
private Date dob;
}