Spring 3.1 JSON 日期格式 [英] Spring 3.1 JSON date format

查看:23
本文介绍了Spring 3.1 JSON 日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using annotated Spring 3.1 MVC code (spring-mvc) and when i send date object through the @RequestBody the date is showing up as numeric. This is my controller

@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();
    }
}

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

When i pass in date, i am able to receive the date in the format. But my browser displays date as numeric

1327682374011

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

How do i make it display date in the format I have registered for the webbinder? I saw in some forum that I should use jackson mapper, but cant i alter the existing mapper?

推荐答案

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

In order to override the default date formatting strategy of Jakson following are the step to follow:

  1. 扩展 JsonSerializer 以创建处理日期格式的新类
  2. 覆盖 serialize(Date date, JsonGenerator gen, SerializerProvider provider) 函数以您想要的格式格式化日期并将其写回生成器实例 (gen)
  3. 使用 @JsonSerialize(using = CustomDateSerializer.class)
  4. 注释您的日期获取器对象以使用扩展的 json 序列化程序
  1. Extend JsonSerializer to create a new class for handling date formatting
  2. Override serialize(Date date, JsonGenerator gen, SerializerProvider provider) function to format date in your desired format and write it back to generator instance (gen)
  3. Annotate your date getter object to use your extended json serializer using @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

这篇关于Spring 3.1 JSON 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆