Serialize Java.util.Date with Jackson JSON Processor

承上篇JSON responce for Jersey without @XmlRootElemen,當我改用JSON時,會發生Date type資料格式不正確的問題,如下圖

解決步驟如下

1. 撰寫一支繼承JsonSerializer的Class,並實作serialize方法,完整程式碼如下
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class JsonDateSerializer extends JsonSerializer< Date> {

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
  throws IOException, JsonProcessingException {
 String formattedDate = dateFormat.format(date);
  gen.writeString(formattedDate);
 }
}

2. 修改前文的Entity(GroupData.java),class加上@JsonAutoDetect,針對要處理的Date欄位,在getter加上@JsonSerialize(using = JsonDateSerializer.class)

@JsonAutoDetect
@XmlRootElement
@Entity
public class GroupData {

   @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int GroupID;

   private String GroupName;

  @Temporal(TemporalType.TIMESTAMP)
  private Date CreateDate;

        //  getter & setter
        public int getGroupID() {
             return GroupID;
   }

   public String getGroupName() {
     return GroupName;
   }

   public void setGroupName(String groupName) {
     GroupName = groupName;
   }

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

   public void setCreateDate(Date createDate) {
     CreateDate = createDate;
   }
}

大功告成

參考文章
How to Serialize Java.util.Date with Jackson JSON Processor / Spring 3.0
How to control Date formatting when Jackson JSON Processor is used with Spring 3.0

沒有留言: