Description
I'm new to Java AND Jackson and I try to save a java.time.duration
to a JSON in a nice and readable hh:mm (hours:minutes) format for storing and retrieving.
In my project I use:
- Jackson
com.fasterxml.jackson.core:jackson-databind:2.14.1
. - Jackson
com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.1
for the support of the newer Java 8 time/date classes.
Minimum working example:
Consider following example class:
public class Book {
private Duration timeToComplete;
public Book(Duration durationToComplete) {
this.timeToComplete = durationToComplete;
}
// default constructor + getter & setter
}
If I try to serialize a book instance into JSON like in the following code section
public class JavaToJson throws JsonProcessingException {
public static void main(String[] args) {
// create the instance of Book, duration 01h:11min
LocalTime startTime = LocalTime.of(13,30);
LocalTime endTime = LocalTime.of(14,41);
Book firstBook = new Book(Duration.between(startTime, endTime));
// create the mapper, add the java8 time support module and enable pretty parsing
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.build()
.enable(SerializationFeature.INDENT_OUTPUT);
// serialize and print to console
System.out.println(objectMapper.writeValueAsString(firstBook));
}
}
it gives me the duration in seconds instead of 01:11
.
{
"timeToComplete" : 4740.000000000
}
How would I change the JSON output into a hh:mm format?
What I tried until now
I thought about adding a custom Serializer/Deserializer (potentially a DurationSerializer
?) during instantiation of the ObjectMapper but it seems I can't make the formatting work...
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
// add the custom serializer for the duration
.addModule(new SimpleModule().addSerializer(new DurationSerializer(){
@Override
protected DurationSerializer withFormat(Boolean useTimestamp, DateTimeFormatter dtf, JsonFormat.Shape shape) {
// here I try to change the formatting
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm");
return super.withFormat(useTimestamp, dtf, shape);
}
}))
.build()
.enable(SerializationFeature.INDENT_OUTPUT);
All it does is change it to this strange textual representation of the Duration:
{
"timeToComplete" : "PT1H11M"
}
So it seems I'm not completely off but the formatting is still not there. Maybe someone can help with the serializing/de-serializing?
Thanks a lot