Jodatime / Spring MVC / Jackson | DateTime格式问题

时间:2012-12-20 00:24:49

标签: spring-mvc jackson jodatime

当我使用@ResponseData时JodaTime被转换为它的完整对象状态,即使我有一个自定义序列化器。

配置:

春季3.1.2 杰克逊1.9.11

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>${jackson.version}</version>
</dependency>

自定义序列化程序:

public class JodaDateTimeJsonSerializer extends JsonSerializer<DateTime> {

    //TODO Bad (hard) code. This should be part of a global system setting through ConfigurationService
    private static final String dateFormat = ("dd/MM/yyyy");

    private static Logger logger = LoggerFactory.getLogger(JodaDateTimeJsonSerializer.class);

    @Override
    public void serialize(DateTime date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        String formattedDate = DateTimeFormat.forPattern(dateFormat).print(date);
        logger.debug("Converted date string: {}", formattedDate);
        gen.writeString(formattedDate);
    }
}

分派器:

 <mvc:annotation-driven />   

用法:

@JsonSerialize(using=JodaDateTimeJsonSerializer.class)
    public DateTime getExpiryDate() {
        return expiryDate;
    }

我得到的输出与此相似:

"dateCreated":{"monthOfYear":12,"yearOfEra":2012,"yearOfCentury":12,"centuryOfEra":20,"millisOfSecond":359,"millisOfDay":53080359,"secondOfMinute":40,"secondOfDay":53080,"minuteOfHour":44,"minuteOfDay":884,"hourOfDay":14,"weekyear":2012,"weekOfWeekyear":51,"year":2012,"dayOfMonth":19,"dayOfWeek":3,"era":1,"dayOfYear":354,"chronology":{"zone":{"fixed":false,"cachable":false,"id":"Asia/Riyadh"}},"millis":1355917480359,"zone":{"fixed":false,"cachable":false,"id":"Asia/Riyadh"},"afterNow":false,"beforeNow":true,"equalNow":false},"dateModified":{"monthOfYear":12,"yearOfEra":2012,"yearOfCentury":12,"centuryOfEra":20,"millisOfSecond":359,"millisOfDay":53080359,"secondOfMinute":40,"secondOfDa

我想要一个简单的dd / mm / yyyy日期。

请建议。

此外,如何在全局范围内设置此格式规则,而不必一直使用@JsonSerialize。

3 个答案:

答案 0 :(得分:3)

This link帮助解决了这个问题。

基本上你需要一个用于jackson的Serializer和自定义对象映射器。

序列化器:

public class JodaDateTimeJsonSerializer extends JsonSerializer<DateTime> {

    private static final String dateFormat = ("dd/MM/yyyy");

    private static Logger logger = LoggerFactory.getLogger(JodaDateTimeJsonSerializer.class);

    @Override
    public void serialize(DateTime date, JsonGenerator json, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        String formattedDate = DateTimeFormat.forPattern(dateFormat).print(date);
        json.writeString(formattedDate);
    }
}

自定义对象映射器:

public class CustomJacksonObjectMapper extends ObjectMapper {

    public CustomJacksonObjectMapper(){
        CustomSerializerFactory factory = new CustomSerializerFactory();
        factory.addSpecificMapping(DateTime.class, new JodaDateTimeJsonSerializer());
        this.setSerializerFactory(factory);
    }

}

现在使用MVC注册自定义映射器

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                    <property name="objectMapper" ref="customJacksonMapper" />
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>   

这很有效。

答案 1 :(得分:1)

有一个jackson-datatype-joda模块可以用于此 - 请参阅我的答案:https://stackoverflow.com/a/14185077/125246

答案 2 :(得分:0)

正如paulcm所提到的,有一个jackson jodatype模块,它允许在没有@JsonSerializer的情况下进行序列化。您可以在此处查看工作配置https://stackoverflow.com/a/14399927/1134683