spring-mvc - Jodatime/Spring MVC/ jackson |日期时间格式问题

标签 spring-mvc jackson jodatime

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

配置:

Spring 3.1.2 jackson 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 的情况下全局设置此格式化规则。

最佳答案

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

基本上,您需要一个用于 jackson 的序列化程序和自定义对象映射器。

序列化器:

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>   

那行得通。

关于spring-mvc - Jodatime/Spring MVC/ jackson |日期时间格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13963447/

相关文章:

javascript - 用于重定向按钮上的不同页面,使用数组提交到 spring Controller()

java - 关于夏令时的时差

java - Spring 验证错误生成

java - 如何处理响应代码?

java - 未找到具有 URI 的 HTTP 请求的映射....在名称为 'main' 的 DispatcherServlet 中

java - 将 Joda 时间与 IATA 时区一起使用

java - 如何更改 joda time DateTime 对象的小时和分钟?

java - Dropwizard @QueryParam 返回 null 而不是读取参数

java - 如何在 spring 应用程序中注册自定义 jackson 过滤器?

java - Jackson在同一个类中根据json映射不同的属性