I have a string value containing ISO8601 duration string (P3Y6M4DT12H30M5S). How to deserialize it to Duration and Period object using Jackson ? I know that Duration accepts days, hours, minutes, seconds and Period years and months.
3 Answers
tl;dr
org.threeten.extra.PeriodDuration.parse( "P3Y6M4DT12H30M5S" ) ;
Details
- A
Period
represents a span of time on the scale of years, months, days. - A
Duration
represents a span of time on the scale of hours, minutes, seconds, and nanoseconds.
A note of caution: Combining those two concepts into one, as seen in your example input string, rarely makes sense in practice.
PeriodDuration
class
However, if you insist on using such values, there is a class for that. Add the ThreeTen-Extra library to your project. You can then access the PeriodDuration
class.
No need to define a formatting pattern. Your input complies with the ISO 8601 standard. The java.time classes use the standard formats by default when parsing/generating text.
org.threeten.extra.PeriodDuration pd = PeriodDuration.parse( "P3Y6M4DT12H30M5S" ) ;
Generate text in standard ISO 8601 format.
String output = pd.toString() ;
You’ll find several handy methods on that class for construction, normalizing, math (addition, subtraction, negation), and more.
As for Jackson, I’m not a user. I don’t know how to use a third-party class as an automatic formatter in Jackson.

- 303,325
- 100
- 852
- 1,154
I didnt want use external dependency to use such simple approach so I implemented it by myself.
I created PeriodDuration class which contain Period and Duration fields.
Next I created deserializer which extends StdDeserializer and annotated PeriodDuration class with @JsonDeserializer(using = "nameOfMyCustomDeserializer.class)
. That deserializer split iso8601 duration string into two string, before 'T' and after 'T'. If period part is empty then set Period.ZERO but if duration partis empty then set Duration.ZERO.

- 147
- 1
- 12
Add com.fasterxml.jackson.datatype.jsr310.JavaTimeModule to your JsonMapper/ObjectMapper - see https://github.com/FasterXML/jackson-modules-java8.
For serialization, you will need to disable SerializationFeature.WRITE_DATES_AS_TIMESTAMPS - this is enabled, by default. When disabled the duration is output is ISO-8601 format (eg PT12H for 12 hours).

- 953
- 5
- 13