我在哪里指定Spring 3.1中的Jackson SerializationConfig.Feature设置

Bre*_*yan 10 java spring json spring-mvc jackson

我很困惑为什么使用默认包含的jackson,Spring似乎已经定制了默认的Jackson配置.

其中一个令人不安的设置是WRITE_DATES_AS_TIMESTAMPS,杰克逊的默认值是,true然而Spring已经改变了这一点false并且还提供了日期格式.

世界在哪里发生这种情况?我希望我的日期保持序列化为数字.

更新:事实证明它不是导致问题的弹簧,它实际上是休眠导致问题的代理类.出于某种原因,如果hibernate有一个类型映射,type="date"它将序列化作为日期字符串,但是如果type="timestamp"它按预期串行化.而不是花太多时间研究这个,我决定暂时改变我的所有映射到时间戳.

Joe*_*don 15

从3.1 M1开始,您可以通过注册HttpMessageConverters一个子元素来指定jackson自定义配置mvc:annotation-driven.

请参见Spring 3.1 MVC命名空间改进

请参阅SPR-7504更容易将新的消息转换器添加到AnnotationMethodHandlerAdapter

例:

<bean id="jacksonObjectMapper" class="x.y.z.CustomObjectMapper">                
</bean>

<mvc:annotation-driven>
    <mvc:message-converters>
       <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
           <property name="objectMapper" ref="jacksonObjectMapper" />
       </bean>
       </mvc:message-converters>
</mvc:annotation-driven>
Run Code Online (Sandbox Code Playgroud)

CustomObjectMapper对象

    @Component("jacksonObjectMapper")
    public class CustomObjectMapper extends ObjectMapper {

        @PostConstruct
        public void afterPropertiesSet() throws Exception {

            SerializationConfig serialConfig = getSerializationConfig()     
                        .withDateFormat(null);

                  //any other configuration

            this.setSerializationConfig(serialConfig);
        }
    }
Run Code Online (Sandbox Code Playgroud)

SerializationConfig .withDateFormat

除了使用指定的日期格式构造实例外,还将启用或禁用Feature.WRITE_DATES_AS_TIMESTAMPS(如果格式设置为null,则启用;如果非null则禁用)