【问题标题】:Jodatime/Spring MVC/Jackson | DateTime formatting issueJodatime/Spring MVC/杰克逊 |日期时间格式问题
【发布时间】:2012-12-07 10:59:48
【问题描述】:

当我使用 @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 的情况下全局设置此格式规则。

【问题讨论】:

    标签: spring-mvc jackson jodatime


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      有一个 jackson-datatype-joda 模块可用于此 - 请在此处查看我的答案:https://stackoverflow.com/a/14185077/125246

      【讨论】:

      • 我会假设由于上述是杰克逊 2.0+ 和原始问题状态杰克逊 1.9。
      【解决方案3】:

      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>   
      

      这行得通。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-12
        • 2014-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多