gpt4 book ai didi

java - 使用 Jackson 反序列化 LocalDateTime

转载 作者:行者123 更新时间:2023-11-30 10:21:18 25 4
gpt4 key购买 nike

当我尝试反序列化这个属性时出现错误:

@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime deliveryDate;

这是反序列化类:

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {

if (parser.getCurrentToken().equals(JsonToken.VALUE_STRING)) {
String rawDate = parser.getText();
return LocalDateTime.parse(rawDate);
} else {
throw context.wrongTokenException(parser, JsonToken.VALUE_STRING, "Expected string.");
}
}

和序列化类:

public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

gen.writeString(value.toString());
}

这是我得到的错误:

"timestamp":1513962011642,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Could not read document: Text '2017-12-22T16:00:00.874Z' could not be parsed, unparsed text found at index 23 

你知道为什么吗?

谢谢!

最佳答案

tl;dr

进程作为 Instant而不是 LocalDateTime .

Instant.parse( "2017-12-22T16:00:00.874Z" )

详情

不确定来自 JSON 的原始数据。如果您的输入数据是 1513962011642,它似乎是一个纪元以来的计数,大概是一个 epoch reference date。 1970-01-01T00:00:00Z,UTC 时间 1970 年的第一刻。

Instant instant = Instant.ofEpochMilli( 1_513_962_011_642L ) ;

如果原始输入是2017-12-22T16:00:00.874Z,直接解析为Instant。该字符串在标准 ISO 8601 中格式。末尾的 ZZulu 的缩写,表示 UTC。

java.time 类在解析/生成字符串时默认使用标准格式。

Instant instant = Instant.parse( "2017-12-22T16:00:00.874Z" ) ;

A LocalDateTime故意缺少任何 time zone 的概念或 offset from UTC ,所以它代表一个实际时刻,也不是时间轴上的一个点。您错误地试图将您的值放入错误的类中,无法表示它是 UTC 值这一事实。

相反,将该输入处理为 Instant 对象。一个瞬间代表时间轴上的一个点 UTC分辨率为 nanoseconds .

关于java - 使用 Jackson 反序列化 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47945123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com