您可以指定带有可选部分(由[] 分隔)的模式,以指示偏移量可以有两种不同的格式,并使用@JsonFormat 注释将其添加到相应的字段中。
我已经创建了这个测试类:
public class SampleType {
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss[XXX][XX]")
private ZonedDateTime date;
// getter and setter
}
注意最后一部分 ([XXX][XX]):每对 [] 是一个可选部分,因此解析器会尝试解析每一对(如果存在)。 XXX 是带有: 的偏移量,XX 是没有它的偏移量(更多详细信息,请查看javadoc)
这样,两种格式都可以读取:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
// offset with ":"
String json = "{ \"date\": \"2017-03-28T14:40:00+01:00\" }";
SampleType value = mapper.readValue(json, SampleType.class);
System.out.println(value.getDate()); // 2017-03-28T13:40Z[UTC]
// offset without ":"
json = "{ \"date\": \"2017-03-28T14:40:00+0100\" }";
value = mapper.readValue(json, SampleType.class);
System.out.println(value.getDate()); // 2017-03-28T13:40Z[UTC]
请注意,生成的 ZonedDateTime 的值将转换为 UTC:2017-03-28T13:40Z[UTC]
如果要保持原来的偏移量,只需使用com.fasterxml.jackson.databind.DeserializationFeature类配置ObjectMapper即可:
// add this to preserve the same offset (don't convert to UTC)
mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);
这样,偏移量被保留(值不会转换为 UTC),上面测试的输出将是 2017-03-28T14:40+01:00。