Askolein
Askolein

Reputation: 3378

Spring boot: LocalTime serialization with ISO format

In a very simple Spring-boot reactive project, with no specific configuration (but the one attempted below), I need to serialize LocalTime (and related classes like LocalDate too) in an ISO form. By default each property is serialized individually, which makes sense from an Object point of view. But I need single string property in ISO format.

Several mentions of that issue have been made, like here, here or in lesser extent here.

None work. I wonder what I do wrong or if these links are just outdated and the mechanism in spring updated/changed since.

The central test I've made is by having a bean register the appropriate module:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class MyConfiguration {

    @Bean
    @Primary
    public ObjectMapper customJson() {
        ObjectMapper mapper = new Jackson2ObjectMapperBuilder()
                .build();

        mapper.registerModule(new JavaTimeModule());
        return mapper;
    }
}

My way of identifying that the serialization is not in the ISO format is by looking at my swagger-ui description of my object showing my endTime property as follows (when the actual result I'm trying to achieve is "endTime": "some ISO string"):

"endTime": {
  "hour": 0,
  "minute": 0,
  "nano": 0,
  "second": 0
},

So the question is: How do I configure single string formatting for LocalDate in Spring Boot (Reactive)?

Upvotes: 1

Views: 2134

Answers (2)

Michael Gantman
Michael Gantman

Reputation: 7790

You will need to do something like this:

public static void main(String[] args) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    System.out.println(objectMapper.writeValueAsString(new Entity()));
}

static class Entity {
    LocalTime time = LocalTime.now();

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss.SSS")
    public ZonedDateTime getTime() {
        return time;
    }
}

This is a modified quote from this this question

Upvotes: 1

midhun mathew
midhun mathew

Reputation: 343

You can achieve your objective by disabling the WRITE_DATES_AS_TIMESTAMPS feature in jackson

ObjectMapper mapper = Jackson2ObjectMapperBuilder.json()
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) 
                .modules(new JavaTimeModule())
                .build();

This will make is serialize it in ISO format

Upvotes: 0

Related Questions