Jackson ObjectMapper序列化的字符串日期格式不正确。

huangapple go评论72阅读模式
英文:

Jackson ObjectMapper serialised String date incorrectly

问题

在使用FasterXML ObjectMapper进行序列化时,遇到了duedate在序列化时设置不正确的问题。updatedcreated在映射时是正常的。唯一的区别是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;

通过这个改变,您将保留日期而不进行转换。在其他情况下,您可以使用OffsetDateTimeZonedDateTime来保留原始日期。

希望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.

huangapple
  • 本文由 发表于 2020年9月5日 05:00:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63747982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定