Spring mvc3 jackson格式日期

来源:互联网 发布:opengl 纹理变形算法 编辑:程序博客网 时间:2024/05/01 00:24
 首先需要引入jackson的maven依赖。
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.2</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-lgpl</artifactId>
        <version>1.9.2</version>
    </dependency>
 
  创建一个类继承JsonSerializer<T>, 再使用@Component注解该类
 
 
@Componentpublic class JsonDateSerializer extends JsonSerializer<Date>{        private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;        @Override    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)            throws IOException, JsonProcessingException    {                  String formatDate =  sdf.format(value) ;        jgen.writeString(formatDate);            }}



最后在实体类中使用,要在Date类型属性的get方法上使用。

@JsonSerialize(using=JsonDateSerializer.class)    public Date getCreateDate(){     return createDate;    }

0 0