Spring Boot Sql Date Timestamp Json Serialization Issue

esthrim :

I'm using spring boot 2, and I have a class which has java.sql.Date and also java.sql.Timestamp properties. I need to serialize the Timestamp as nanoseconds and serialize the Date as standard format (yyyy-MM-dd).

At first the JSON result is like below :

 "checkinTime": "2019-05-01T17:00:00.000+0000", // java.sql.Timestamp
 "lastOrderDate":"2019-05-01"    // java.sql.Date

And then I put these lines in the application.properties file

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS: true
spring.jackson.serialization.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS: false

After that the result is like below :

 "checkinTime": -2209014000000,
 "lastOrderDate": 1556643600000,

What I want is like this

 "checkinTime": -2209014000000,   // java.sql.Timestamp
 "lastOrderDate":"2019-05-01"    // java.sql.Date

How can I achieve this in spring boot ??

mrkurtan :

You can always use a custom formatter on any fields or types. You have to have a custom formatter class and add that on your Object Mapper bean. It can be added in Java code or Xml config too. If you have your own view resolver, just make sure that it uses your customer object mapper.

The formatter can be like this for example:

public class CustomDateFormatter extends JsonSerializer<Date> {

    private final DateTimeFormatter formatter;

    public CustomDateFormatter() {
        formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
    }

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String str = formatter.format(value.toLocalDate());
        gen.writeString(str);
    }
}

And object mapper bean init with wiring up with a view resolver:

private ObjectMapper customObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Date.class, new CustomDateFormatter());
    mapper.registerModule(module);
    mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    mapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
    return mapper;
}

private MappingJackson2JsonView jsonView() {
    MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setObjectMapper(customObjectMapper());
    return view;
}

@Bean
public ContentNegotiatingViewResolver viewResolver() {
    ContentNegotiatingViewResolver cnvr = new ContentNegotiatingViewResolver();
    List<View> viewList = new ArrayList<>();
    viewList.add(jsonView());
    cnvr.setDefaultViews(viewList);
    return cnvr;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135400&siteId=1