大廈@ miklov-kriven的非常有用的答案,我希望考慮這兩個附加分證明是有益的人:
(1)我覺得這是一個不錯的主意,包括串行器和解串器的靜態內部班級在同一班。注意,使用ThreadLocal來實現SimpleDateFormat的線程安全。
public class DateConverter {
private static final ThreadLocal<SimpleDateFormat> sdf =
ThreadLocal.<SimpleDateFormat>withInitial(
() -> {return new SimpleDateFormat("yyyy-MM-dd HH:mm a z");});
public static class Serialize extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen SerializerProvider provider) throws Exception {
if (value == null) {
jgen.writeNull();
}
else {
jgen.writeString(sdf.get().format(value));
}
}
}
public static class Deserialize extends JsonDeserializer<Date> {
@Overrride
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws Exception {
String dateAsString = jp.getText();
try {
if (Strings.isNullOrEmpty(dateAsString)) {
return null;
}
else {
return new Date(sdf.get().parse(dateAsString).getTime());
}
}
catch (ParseException pe) {
throw new RuntimeException(pe);
}
}
}
}
(2)作爲替代使用每個單獨的類成員,你也可以考慮通過在應用級應用自定義序列覆蓋傑克遜的默認序列化的@JsonSerialize和@JsonDeserialize註解,這是所有類成員類型Date將由Jackson使用此自定義序列化進行序列化,而不在每個字段上進行明確的註釋。如果您在使用Spring啓動例如一個辦法做到這一點將按如下:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public Module customModule() {
SimpleModule module = new SimpleModule();
module.addSerializer(Date.class, new DateConverter.Serialize());
module.addDeserializer(Date.class, new Dateconverter.Deserialize());
return module;
}
}
如果格式還包含AM/PM指定,12小時格式會更好:DateFormat df = new SimpleDateFormat(「yyyy-MM-dd hh:mm a z」); –
嘗試了所有這些解決方案,但無法將我的POJO的Date變量存儲到Map鍵值中,也作爲Date存儲。 我想要這個從Map實例化一個BasicDbObject(MongoDB API),然後將這個變量作爲Date(不是Long或String)存儲在MongoDB DB集合中。 這甚至可能嗎? 謝謝 – RedEagle
使用Java 8'LocalDateTime'或'ZonedDateTime'代替'Date'是否容易?由於'日期'基本上已被棄用(或至少它的許多方法),我想使用這些替代品。 – houcros