Arockiasamy
Arockiasamy

Reputation: 60

LocalTime into Json - unable to change time format

I have a class like the following

public class TimePeroid implements Comparable<TimePeroid>, Serializable {

    private static final long serialVersionUID = -65707223409901256L;
        
    @Expose
    //@JsonFormat(pattern="HH:mm:ss")
    private LocalTime start;
        
    @Expose
    //@JsonFormat(pattern="HH:mm:ss")
    private LocalTime end;
    //getter setter
}

At response time when I convert it into a JSON string with the help of ObjectMapper, I get a JSON string like below

{
"start" : {"hour":6,"minute":0,"second":0,"nano":0},  
"end":{"hour":18,"minute":0,"second":0,"nano":0}  
}

But I need it like this

{  
"start":"06:00:00",  
"end":"18:00:00"  
}

What I've tried until now

Solution 1

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

Solution 2

@JsonFormat(pattern="HH:mm:ss")

Solution 3

ObjectMapper mapperObj = new ObjectMapper();
                mapperObj.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
                DateFormat df = new SimpleDateFormat("HH:mm");
                mapperObj.setDateFormat(df);

None of them works. please help me on this

Upvotes: 1

Views: 6914

Answers (2)

ptomli
ptomli

Reputation: 11818

Have you included JavaTimeModule in your Jackson configuration?

A related SO question & answer here https://stackoverflow.com/a/32202201/134894

To copy/paste from that answer

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.6.0</version>
</dependency>

and

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

Once you have the module registered, you could also potentially configure the default LocalDate formatting, by registering a serializer.

SimpleModule module = new SimpleModule();
module.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ISO_LOCAL_TIME));
mapper.registerModule(module);

Actually, I see you're using Spring Boot.. so this might be more idiomatic for that environment

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
  return builder -> {
    builder.serializers(new LocalTimeSerializer(DateTimeFormatter.ISO_LOCAL_TIME));
    builder.deserializers(new LocalTimeDeserializer(DateTimeFormatter.ISO_LOCAL_TIME));
    builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
 };
}

Upvotes: 4

You need to use "KK, not "HH"

Code Below: @JsonFormat(pattern="KK:mm")

Upvotes: -1

Related Questions