springboot配置自定义objectMapper
package com.my.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
@Slf4j
@Configuration
public class ConfigObjectMapper {
@Bean("objectMapper")
public ObjectMapper objectMapper() {
Jackson2ObjectMapperFactoryBean objectMapper = new Jackson2ObjectMapperFactoryBean();
Object[] objects = {
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
, DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS
, DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE
, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
, DeserializationFeature.FAIL_ON_INVALID_SUBTYPE
};
objectMapper.setFeaturesToDisable(objects);
objectMapper.setModulesToInstall(CustomModule.class);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setFindModulesViaServiceLoader(true);
objectMapper.afterPropertiesSet();
return objectMapper.getObject();
}
@Bean
public MessageConverter messageConverter(@Qualifier("objectMapper") ObjectMapper objectMapper) {
return new Jackson2JsonMessageConverter(objectMapper);
}
public static class CustomModule extends SimpleModule {
private static final long serialVersionUID = 1L;
/**
* Custom Jackson Module to serialize ZoneDateTime into desired format.
*/
public CustomModule() {
this.addSerializer(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
@Override
public void serialize(ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(zonedDateTime));
}
});
}
}
}
end.