【问题标题】:Spring 3.1 JSON date formatSpring 3.1 JSON 日期格式
【发布时间】:2012-02-20 17:17:13
【问题描述】:

我正在使用带注释的 Spring 3.1 MVC 代码 (spring-mvc),当我通过 @RequestBody 发送日期对象时,日期显示为数字。 这是我的控制器

@Controller
@RequestMapping("/test")
public class MyController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class,
                  new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }


    @RequestMapping(value = "/getdate", method = RequestMethod.GET)
    public @ResponseBody Date getDate(@RequestParam("dt") Date dt, Model model) {
        // dt is properly constructed here..
        return new Date();
    }
}

当我传入日期时,我能够以格式接收日期。 但是我的浏览器将日期显示为数字

1327682374011

如何让它以我为 webbinder 注册的格式显示日期? 我在某个论坛看到我应该使用jackson mapper,但是我不能改变现有的mapper吗?

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    为了覆盖 Jakson 的默认日期格式化策略,需要遵循以下步骤:

    1. 扩展JsonSerializer 以创建一个用于处理日期格式的新类
    2. 覆盖 serialize(Date date, JsonGenerator gen, SerializerProvider provider) 函数以将日期格式化为所需格式并将其写回生成器实例 (gen)
    3. 使用 @JsonSerialize(using = CustomDateSerializer.class) 注释您的日期获取器对象以使用您的扩展 json 序列化程序

    代码:

    //CustomDateSerializer class
    public class CustomDateSerializer extends JsonSerializer<Date> {    
        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws 
            IOException, JsonProcessingException {      
    
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = formatter.format(value);
    
            gen.writeString(formattedDate);
    
        }
    }
    
    
    //date getter method
    @JsonSerialize(using = CustomDateSerializer.class)
    public Date getDate() {
        return date;
    }
    

    来源:http://blog.seyfi.net/2010/03/how-to-control-date-formatting-when.html

    【讨论】:

    • 感谢瓦卡斯。我想知道 spring 中的默认 JSON 序列化器是如何工作的,因为我在类路径中没有杰克逊罐子。可能它不使用杰克逊。
    • @M.AtifRiaz 用户自 2012 年 10 月 22 日 18:27 以来未处于活动状态。 :)
    【解决方案2】:

    或者,如果您使用 jackson 并希望在所有日期(不仅仅是您注释的日期)上使用 ISO-8601 日期,您可以禁用将日期写入时间戳的默认设置。

    <bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
    <bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig" factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="jacksonSerializationConfig" />
        <property name="targetMethod" value="disable" />
        <property name="arguments">
            <list>
                <value type="org.codehaus.jackson.map.SerializationConfig.Feature">WRITE_DATES_AS_TIMESTAMPS</value>
            </list>
        </property>
    </bean>
    

    然后,如果您想将日期转换为默认格式以外的其他格式,您可以这样做:

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="jacksonSerializationConfig" />
        <property name="targetMethod" value="setDateFormat" />
        <property name="arguments">
            <list>
              <bean class="java.text.SimpleDateFormat">
                <constructor-arg value="yyyy-MM-dd'T'HH:mm:ssZ"/>
              </bean>
            </list>
        </property>
    </bean>
    

    【讨论】:

      【解决方案3】:

      这是一种更标准的配置方法,使用 ISO8601 日期,这是我为您的 API 推荐的方法。

      <!-- you can't call it objectMapper for some reason -->
      <bean name="jacksonObjectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
          <property name="featuresToDisable">
              <array>
                  <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS"/>
              </array>
          </property>
      </bean>
      
      <!-- setup spring MVC -->
      <mvc:annotation-driven>
          <mvc:message-converters register-defaults="true">
              <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                  <property name="objectMapper" ref="jacksonObjectMapper"/>
              </bean>
          </mvc:message-converters>
      </mvc:annotation-driven>
      

      这里是附加文档:

      【讨论】:

        猜你喜欢
        • 2017-04-19
        • 1970-01-01
        • 2015-05-18
        • 2015-05-20
        • 2022-01-06
        • 2016-12-16
        • 1970-01-01
        • 2015-06-21
        • 1970-01-01
        相关资源
        最近更新 更多