もちろん、シリアル化と逆シリアル化と呼ばれる自動化された方法があり、pb2qでも言及されているように、特定のアノテーション( @ JsonSerialize、@ JsonDeserialize)を使用して定義できます。
java.util.Dateとjava.util.Calendar...の両方を使用でき、おそらくJodaTimeも使用できます。
@JsonFormatアノテーションは、逆シリアル化(シリアル化は完全に機能しました)中に私が望んでいたように機能しませんでした(タイムゾーンを異なる値に調整しました):
@JsonFormat(locale = "hu", shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm", timezone = "CET")
@JsonFormat(locale = "hu", shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm", timezone = "Europe/Budapest")
予測結果が必要な場合は、@JsonFormatアノテーションの代わりにカスタムシリアライザーとカスタムデシリアライザーを使用する必要があります。私はここで本当に良いチュートリアルと解決策を見つけましたhttp://www.baeldung.com/jackson-serialize-dates
日付フィールドの例がありますが、カレンダーフィールドが必要だったので、ここに私の実装があります:
シリアライザークラス:
public class CustomCalendarSerializer extends JsonSerializer<Calendar> {
public static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public static final Locale LOCALE_HUNGARIAN = new Locale("hu", "HU");
public static final TimeZone LOCAL_TIME_ZONE = TimeZone.getTimeZone("Europe/Budapest");
@Override
public void serialize(Calendar value, JsonGenerator gen, SerializerProvider arg2)
throws IOException, JsonProcessingException {
if (value == null) {
gen.writeNull();
} else {
gen.writeString(FORMATTER.format(value.getTime()));
}
}
}
デシリアライザークラス:
public class CustomCalendarDeserializer extends JsonDeserializer<Calendar> {
@Override
public Calendar deserialize(JsonParser jsonparser, DeserializationContext context)
throws IOException, JsonProcessingException {
String dateAsString = jsonparser.getText();
try {
Date date = CustomCalendarSerializer.FORMATTER.parse(dateAsString);
Calendar calendar = Calendar.getInstance(
CustomCalendarSerializer.LOCAL_TIME_ZONE,
CustomCalendarSerializer.LOCALE_HUNGARIAN
);
calendar.setTime(date);
return calendar;
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
および上記のクラスの使用法:
public class CalendarEntry {
@JsonSerialize(using = CustomCalendarSerializer.class)
@JsonDeserialize(using = CustomCalendarDeserializer.class)
private Calendar calendar;
// ... additional things ...
}
この実装を使用すると、シリアル化および逆シリアル化プロセスを連続して実行すると、元の値が生成されます。
@JsonFormatアノテーションを使用するだけで、逆シリアル化によって異なる結果が得られると思います。これは、ライブラリの内部タイムゾーンのデフォルト設定のため、アノテーションパラメータで変更できないものです(これは、Jacksonライブラリ2.5.3および2.6.3バージョンでの私の経験でもあります)。