Jackson Object Mapper in spring MVC not working

前端 未结 2 1569
傲寒
傲寒 2020-12-18 11:10

Every object with Date format is being serialized as a long.

I\'ve read around that I need to create a custom object mapper

and so I did:

pub         


        
相关标签:
2条回答
  • 2020-12-18 11:39

    You'll need to implement your own Dateserializer, just like the following (got it from this 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 could just add the following annotation to your Date-Objects and it will persist fine:

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

    At least it works with spring 3.2.4 and jackson 1.9.13 here.

    edit: Think about using FastDateFormat instead of SimpleDateFormat, for it's the threadsafe-alternative (as mentioned in the comments of Loianes article)

    0 讨论(0)
  • 2020-12-18 11:49

    Try adding 0 as 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 讨论(0)
提交回复
热议问题