Spring 3.1 JSON日期格式

moh*_*moh 31 java spring spring-mvc

我正在使用带注释的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我通过日期时,我能够以格式收到日期.但我的浏览器将日期显示为数字

1327682374011
Run Code Online (Sandbox Code Playgroud)

如何以我为webbinder注册的格式显示日期?我在一些论坛上看到我应该使用杰克逊映射器,但我不能改变现有的映射器?

Waq*_*qas 47

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

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

码:

//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;
}
Run Code Online (Sandbox Code Playgroud)

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


Joh*_*pal 16

或者,如果您使用的是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>
Run Code Online (Sandbox Code Playgroud)

然后,如果要将日期转换为默认格式以外的其他格式,则可以执行以下操作:

<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>
Run Code Online (Sandbox Code Playgroud)


use*_*274 5

以下是使用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>
Run Code Online (Sandbox Code Playgroud)

这是其他文档: