It's easy to create a custom ObjectMapper for Spring, but XML is required for configuration. I am trying to reduce the amount of XML configuration for things that really won't change without requiring a relocation of my entire system.
So the title says it all - can I use annotations or some other method other than XML to tell Spring: "Hey, please use my custom mapper pls object"?
EDIT:
This does not work
@Configuration @EnableWebMvc public class AppConfig { @Primary @Bean public ObjectMapper mapper(){ ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); mapper.registerModule(new JodaModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); return mapper; } }
EDIT 2: I don't think Spring uses my ObjectMapper. I have this code:
@Primary @Bean public ObjectMapper mapper(){ ObjectMapper mapper = new ObjectMapper(); JodaModule mod = new JodaModule(); mod.addSerializer(DateTime.class, new JsonSerializer<DateTime>() { @Override public void serialize(DateTime dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { System.out.println("Hi, bob"); } }); mapper.registerModule(mod); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.INDENT_OUTPUT); return mapper; }
but when I set a breakpoint on System.out.println("Hi, bob") , it is never called - although I definitely serialize DateTime.
source share