我正在Spring Boot中实现应用程序。使用杰克逊。
无论如何,是否有指定JsonFormat来解析两种类型的日期,例如:
2020-10-06T10:15:30+01:00
2020-10-06T10:15:30
我当前的字段:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss Z")
private OffsetDateTime interval;
我是否必须在配置中指定一些ObjectMapper?
我正在检索此错误:
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.OffsetDateTime` from String "2020-10-06T10:15:30+01:00": Failed to deserialize java.time.OffsetDateTime: (java.time.format.DateTimeParseException) Text '2020-10-06T10:15:30+01:00' could not be parsed at index 10
致谢
答案 0 :(得分:2)
您需要使用具有可选区域偏移的JsonDeserializer
进行解析,因此需要自定义public class OffsetDateTimeOptionalZoneDeserializer extends StdScalarDeserializer<OffsetDateTime> {
private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendOffsetId()
.optionalEnd()
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter();
public OffsetDateTimeOptionalZoneDeserializer() { super(OffsetDateTime.class); }
@Override
public OffsetDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return OffsetDateTime.parse(p.getText(), formatter);
}
}
:
public class Test {
@JsonDeserialize(using = OffsetDateTimeOptionalZoneDeserializer.class)
private OffsetDateTime interval;
public static void main(String[] args) throws Exception {
String json = "[" +
"{ \"interval\": \"2020-10-06T10:15:30+01:00\" }," +
"{ \"interval\": \"2020-10-06T10:15:30Z\" }," +
"{ \"interval\": \"2020-10-06T10:15:30\" }" +
"]";
ObjectMapper mapper = new ObjectMapper();
Test[] tests = mapper.readValue(json, Test[].class);
for (Test t : tests)
System.out.println(t.interval);
}
}
测试
2020-10-06T10:15:30+01:00
2020-10-06T10:15:30Z
2020-10-06T10:15:30Z
输出
{{1}}