英文:
Jackson ObjectMapper serialised String date incorrectly
问题
在使用FasterXML ObjectMapper进行序列化时,遇到了duedate
在序列化时设置不正确的问题。updated
和created
在映射时是正常的。唯一的区别是duedate
中不包括小时,并且没有提供小时信息。
"fields": {
"updated": "2020-09-01T06:18:36.000+0900",
"duedate": "2020-08-04",
"created": "2020-07-31T08:25:54.000+0900"
}
这是我的代码:
ObjectMapper mapper = new ObjectMapper();
Fields fields = mapper.readValue(json, Fields.class);
System.out.println(fields.getFields().getDuedate());
结果:Mon Aug 03 19:00:00 CDT 2020
如您所见,日期差了一天,而且不清楚小时是从哪里来的。正确的结果应该是:Tue Aug 04 00:00:00 CDT 2020
。
英文:
Having an issue with the FasterXML ObjectMapper setting the duedate
incorrectly when serializing. updated
and created
are fine when mapping. Only difference is the hours are not included and are not provided.
"fields": {
"updated": "2020-09-01T06:18:36.000+0900",
"duedate": "2020-08-04",
"created": "2020-07-31T08:25:54.000+0900"
}
This is my code:
ObjectMapper mapper = new ObjectMapper();
Fields fields = mapper.readValue(json, Fields.class);
System.out.println(fields.getFields().getDuedate());
Result: Mon Aug 03 19:00:00 CDT 2020
As you can see its off by a day and dont know where the hours came from. The result should be: Tue Aug 04 00:00:00 CDT 2020
答案1
得分: 1
Java默认使用本地时区,并将所有日期转换为本地时区。如果您使用jdk8及更高版本,并且需要保留日期,您需要使用以下代码:
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate duedate;
通过这个改变,您将保留日期而不进行转换。在其他情况下,您可以使用OffsetDateTime
或ZonedDateTime
来保留原始日期。
希望LocalDate
适用于您。
英文:
Java is taken your local time zone by default, and convert all the dates in your local time zone, in your case if your are using jdk8 and up, and you need to keep the date your need to use:
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate duedate;
with this change your ar going to keed the date without transformation, and you can use OffsetDateTime
or ZonedDateTime
in the other cases to keep the original date.
I hope LocalDate
works for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论