1

I am using SpringBoot 2.2. date format is "validFrom": "2013-12-31T18:30:00.000+0000" But I want in number format (like 1411471800000). In my entity I included the below code snippet which worked in Number format.

@JsonProperty("updDate")
**@JsonFormat(shape = JsonFormat.Shape.NUMBER)**
private Date updDate;

To achieve that, I will have to do in all my entities.Is there a way where I can make one change and it will apply for all date formats.

Please advise

Kalyan N
  • 31
  • 2
  • Please try `spring.jackson.date-format= # Date format string (e.g. yyyy-MM-dd HH:mm:ss), or a fully-qualified date format class name (e.g. com.fasterxml.jackson.databind.util.ISO8601DateFormat)` in your aplication.properties file of spring book. – Ashish Karn Jul 04 '20 at 10:16

1 Answers1

0

You can use custom Serializer for Date type which will used to serialize Date type.

public class DateSerializer extends StdSerializer<Date> {

  private static final long serialVersionUID = -7880057299936791237L;

  public JacksonLocalDateSerializer() {
    this(null);
  }

  public JacksonLocalDateSerializer(Class<Date> type) {
    super(type);
  }

  @Override
  public void serialize(Date value, JsonGenerator jsonGenerator,
      SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
    jsonGenerator.writeNumber(value.getTime());
  }
}

and add it in object mapper so that Date type object always serialize using your custom serializer

@Configuration
public class JacksonConfig {
    
    @Bean
    @Primary
    public ObjectMapper configureObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(Date.class, new DateSerializer());
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }
}
Eklavya
  • 17,618
  • 4
  • 28
  • 57