Jackson Object Mapper in spring MVC not working

Each object with a date format is serialized as long.

I read that I need to create a custom object mapping

and so I did:

public class CustomObjectMapper extends ObjectMapper { public CustomObjectMapper() { super(); configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false); setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); } } 

I also registered this custom mapper as a converter

 @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(converter()); addDefaultHttpMessageConverters(converters); } @Bean MappingJacksonHttpMessageConverter converter() { MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter(); converter.setObjectMapper(new CustomObjectMapper()); return converter; } 

but nonetheless it does not work and I get a long date.

Any idea what I'm doing wrong?

+3
source share
2 answers

You will need to implement your own Dateserializer, as well as the following (received this from the tutorial , so props to Loiane, not me ;-)):

 package ....util.json; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import org.springframework.stereotype.Component; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; @Component public class JsonDateSerializer extends JsonSerializer<Date>{ private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm "); // change according to your needs @Override public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException { String formattedDate = dateFormat.format(date); gen.writeString(formattedDate); } } 

then you can simply add the following annotation to your Date-Objects and it will persist normally:

 @JsonSerialize(using = JsonDateSerializer.class) public Date getCreated() { return created; } 

At least it works with spring 3.2.4 and jackson 1.9.13.

edit: Think about using FastDateFormat instead of SimpleDateFormat , for it is an alternative to threadsafe-alternative (as indicated in the comments of the Loianes article)

+3
source

Try adding 0 as an index in #add ()

 @Configuration @ComponentScan() @EnableWebMvc @PropertySource("classpath:/web.properties") public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) { converters.add(0, jsonConverter()); } @Bean public MappingJacksonHttpMessageConverter jsonConverter() { final MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter(); converter.setObjectMapper(new CustomObjectMapper()); return converter; } } 

It worked for me.

0
source

All Articles