カスタム日付形式のシリアライザー/デシリアライザーを作成できます。
デシリアライザーの場合:
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;
}