How to serialize LocalDateTime with Jackson?

I got the following code snippet:

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, "Day of the week": "Thursday", "month": " January "," DAYOFMONTH ": 19," year ": 2017," monthValue ": 1," timeline ": {" ID ":" ISO "," calendarType ":" ISO8601 "}}}

What I want to achieve is a string in ISO8601

2017-01-19T18: 36: 51Z

+5
source share
2 answers

Perhaps this is due to an error in the code. You used a 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); 
+7
source

This is what you can do for 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. Therefore, you can refuse it. But ISO8601 does not recommend using Local Time as it is ambiguous:

If UTC relationship information is not provided with a time representation, the time is considered local. Although it may be safe to assume local time when communicating in the same time zone, it is ambiguous when used when communicating in different time zones. Even within the same geographical time zone, some local times will be ambiguous if the region observes daylight saving time. It is usually preferable to specify the time zone (zone designation) using standard notation.

+2
source

Source: https://habr.com/ru/post/1263072/


All Articles