4

If I have a POJO field of type A that I want serialized as being of type B, I can easily achieve this with a pair of Converters:

@JsonSerialize(converter=ConvA2B.class)
@JsonDeserialize(converter=ConvB2A.class)
private A field; 

But what if I want all the fields of that type in all the POJOs to be treated like that? Is there a global converters configuration?


To provide a bit of context, I'm trying to serialize java.time.LocalDateTime fields as unix timestamps and one possible solution I found is to convert each field to java.time.Instant with a custom type converter such as:

public static class Conv extends StdConverter<LocalDateTime, Instant> {

    @Override
    public Instant convert(LocalDateTime value) {
        return value.toInstant(ZoneOffset.UTC);
    }

}
watery
  • 5,026
  • 9
  • 52
  • 92

1 Answers1

1

You can configure the ObjectMapper that Jackson uses. In general, you can configure how you want to serialize certain types. For your concrete problem, you could try the following:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

...

private ObjectMapper createObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    return mapper;
}

Now, depending on your application setup, you need to inject/supply/configure the object mapper somewhere.

sfiss
  • 2,119
  • 13
  • 19