2016-02-23 44 views
1

我正在使用Spring 4.1.6创建一个RESTful API。我是而不是使用Spring Boot。我不想用@JsonSerialize(using = MyLocalDateTimeJsonSerializer.class)注释我的每个资源,因为它增加了很多样板。相反,这应该是默认行为。使用Spring MVC如何为java 8 LocalDateTime添加自定义的JsonSerializer?

理想情况下,我想添加一些配置拿起我的自定义LocalDateTime串行器将然后在整个使用。我看到一个例子,让我充满希望,以下是可行的,但事实并非如此。

@Configuration 
@EnableWebMvc 
public class JacksonConfiguration extends WebMvcConfigurerAdapter { 

    @Override 
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { 
     Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder() 
     .serializers(new LocalDateTimeJsonSerializer()); 
     converters.add(new MappingJackson2HttpMessageConverter(builder.build())); 
    } 

} 

public class LocalDateTimeJsonSerializer extends JsonSerializer<LocalDateTime> { 

    @Override 
    public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) 
      throws IOException, JsonProcessingException { 
     jsonGenerator.writeString("foo"); 
    } 

    @Override 
    public Class<LocalDateTime> handledType() { 
     return LocalDateTime.class; 
    } 

} 

我注意到,春节负荷JSR310Module这就要求正在使用addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE)。难道这是在上面的例子之后注册的,所以要优先考虑吗?

有没有一种方法可以在整个代码中使用我自定义的LocalDateTime串行器,而不使用@JsonSerialize

编辑 之所以春DI没有拿起基于注解配置是因为我的项目必须基于XML的配置也一样,其中有<mvc:annotation-driven/>声明。

这似乎覆盖注解的类。从xml中删除这个配置类,扩展WebMvcConfigurerAdapter已被组件扫描和利用。

回答

0

你可以把你所有的串行器/解串器的模块,并公开为com.fasterxml.jackson.databind.module.SimpleModule。 Spring automaticaly注册类型为Module的al豆,并使用它们来配置ObjectMapper。 我正在使用follwoing代码,它的工作原理:

@Component 
public class CommonsModule extends SimpleModule implements RegisterableModule { 
    private static final long serialVersionUID = 1L; 
    public CommonsModule() { 
     addSerializer(LocalDateTime.class, 
new LocalDateTimeJsonSerializer()); 
    } 
} 
+0

恐怕这对我不起作用。 –

相关问题