java 如何使用 Jackson 序列化 LocalDateTime?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41749539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to serialize LocalDateTime with Hymanson?
提问by user1745356
I got the following piece of code:
我得到了以下代码:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String now = new ObjectMapper().writeValueAsString(new SomeClass(LocalDateTime.now()));
System.out.println(now);
And I get this:
我明白了:
{"time":{"hour":20,"minute":49,"second":42,"nano":99000000,"dayOfYear":19,"dayOfWeek":"THURSDAY","month":"JANUARY","dayOfMonth":19,"year":2017,"monthValue":1,"chronology":{"id":"ISO","calendarType":"iso8601"}}}
{"time":{"hour":20,"minute":49,"second":42,"nano":99000000,"dayOfYear":19,"dayOfWeek":"THURSDAY","month":"JANUARY ","dayOfMonth":19,"year":2017,"monthValue":1,"chronology":{"id":"ISO","calendarType":"iso8601"}}}
What I want to achieve is a string in ISO8601
我想要实现的是 ISO8601 中的字符串
2017-01-19T18:36:51Z
2017-01-19T18:36:51Z
回答by Alexander Yanyshin
This is probably due to mistake in your code. You were using new unconfigured instance of mapper, here is the fix:
这可能是由于您的代码中的错误。您正在使用新的未配置映射器实例,这是修复程序:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String now = mapper.writeValueAsString(new SomeClass(LocalDateTime.now()));
System.out.println(now);
回答by Stanislav Bashkyrtsev
This is what you can do for OffsetDateTime
:
这是你可以做的OffsetDateTime
:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSXXXX")
private OffsetDateTime timeOfBirth;
For LocalDateTime you cannot use XXXX (zone offset) because there is no offset information. So you can drop it. But ISO8601 discourages using Local Timeas it's ambiguous:
对于 LocalDateTime,您不能使用 XXXX(区域偏移),因为没有偏移信息。所以你可以放下它。但ISO8601 不鼓励使用本地时间,因为它不明确:
If no UTC relation information is given with a time representation, the time is assumed to be in local time. While it may be safe to assume local time when communicating in the same time zone, it is ambiguous when used in communicating across different time zones. Even within a single geographic time zone, some local times will be ambiguous if the region observes daylight saving time. It is usually preferable to indicate a time zone(zone designator) using the standard's notation.
如果没有给出带有时间表示的 UTC 关系信息,则假定时间为本地时间。虽然在同一时区进行通信时假设本地时间可能是安全的,但在跨不同时区进行通信时使用它是模棱两可的。即使在一个地理时区内,如果该地区遵守夏令时,一些当地时间也会不明确。通常 最好使用标准的符号来指示时区(区域指示符)。