简体   繁体   English

如何使用Jackson和RestTemplate将24小时日期字符串反序列化为LocalDate

[英]How do I deserialize 24 hour date string to LocalDate using Jackson and RestTemplate

I have the following... 我有以下...

public static final String DATE_PATTERN = "yyyy-MM-dd'T'hh:mm:ss.SSSZ";
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_PATTERN)
private LocalDate created;

return this.restTemplate.postForObject(url, entity, SearchResult.class);

When I run the code it errors out with the following... 当我运行代码时,出现以下错误...

java.time.DateTimeException: Invalid value for ClockHourOfAmPm (valid values 1 - 12): 13
    at java.base/java.time.temporal.ValueRange.checkValidValue(ValueRange.java:311) ~[na:na]
    at java.base/java.time.temporal.ChronoField.checkValidValue(ChronoField.java:717) ~[na:na]

How do I deserialize this to a LocalDate? 如何将其反序列化为LocalDate? Regular Java7 date works fine. 常规Java7日期可以正常工作。

The Final Solution Looks like this 最终解决方案如下所示

public static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

public class LocalDateDeserializer extends StdDeserializer<LocalDate>{
    protected LocalDateDeserializer(){
        super(LocalDate.class);
    }
    @Override
    public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return LocalDate.parse(parser.readValueAs(String.class), DateTimeFormatter.ofPattern(JiraService.DATE_PATTERN));
    }
}

public class LocalDateSerializer extends StdSerializer<LocalDate> {

    public LocalDateSerializer() {
        super(LocalDate.class);
    }

    @Override
    public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException {
        generator.writeString(value.format(DateTimeFormatter.ofPattern(JiraService.DATE_PATTERN)));
    }
}

@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate created;

hh is for 1-12 hour format, use HH for 0-23 hour format, see SimpleDateFormat docs. hh是1-12小时格式,请使用HH为0-23小时的格式,请参见SimpleDateFormat的文档。 You need: 你需要:

public static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

Older classes like SimpleDateFormat or Calendar are lenient by default so they are silently fixing the date by moving it forward by the overflowing field offset. 默认情况下,较早的类(如SimpleDateFormatCalendar宽松的 ,因此它们通过将日期向前移动了溢出字段偏移量来静默固定日期。 That's why you are not supposed to use them anymore. 这就是为什么您不应该再使用它们了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM