当然有一种自动化的方式叫做序列化和反序列化,你可以用特定的注解来定义它(@JsonSerialize,@JsonDeserialize) pb2q 也提到过。
您可以同时使用 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
有 Date 字段的示例,但我需要 Calendar 字段,所以这是我的实现:
序列化器类:
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 版本)。