Advertisement
ILyaCyclone

Spring Jackson (JSON) serialization time format

Jan 7th, 2019
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. package cyclone.lunchvoting.config;
  2.  
  3. import com.fasterxml.jackson.core.JsonGenerator;
  4. import com.fasterxml.jackson.core.JsonParser;
  5. import com.fasterxml.jackson.core.JsonProcessingException;
  6. import com.fasterxml.jackson.databind.*;
  7. import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
  8. import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11.  
  12. import java.io.IOException;
  13. import java.time.LocalTime;
  14. import java.time.format.DateTimeFormatter;
  15.  
  16. @Configuration
  17. public class JacksonConfiguration {
  18.     private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
  19.  
  20.     @Bean
  21.     public ObjectMapper objectMapper() {
  22.         ObjectMapper objectMapper = new ObjectMapper();
  23.         // http://lewandowski.io/2016/02/formatting-java-time-with-spring-boot-using-json/
  24.         // I hope there is an easier way to set global time format
  25.         JavaTimeModule javaTimeModule = new JavaTimeModule();
  26.         javaTimeModule.addSerializer(LocalTime.class, new JsonSerializer<LocalTime>() {
  27.             @Override
  28.             public void serialize(LocalTime localTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
  29.                 jsonGenerator.writeString(localTime.format(TIME_FORMATTER));
  30.             }
  31.         });
  32.         javaTimeModule.addDeserializer(LocalTime.class, new JsonDeserializer<LocalTime>() {
  33.             @Override
  34.             public LocalTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
  35.                 return LocalTime.parse(jsonParser.getValueAsString(), TIME_FORMATTER);
  36.             }
  37.         });
  38.  
  39.  
  40.         objectMapper.registerModule(javaTimeModule);
  41.         objectMapper.registerModule(new Hibernate5Module());
  42.         return objectMapper;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement