春季 3.1 JSON 日期格式

2022-09-01 10:24:08

我正在使用带注释的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

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


答案 1

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

  1. 扩展以创建用于处理日期格式设置的新类JsonSerializer
  2. 覆盖函数以将日期格式化为所需格式,并将其写回生成器实例(gen)serialize(Date date, JsonGenerator gen, SerializerProvider provider)
  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;
}

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


答案 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>

推荐