2013-01-14 26 views
2

我在Spring(3.1)數據REST中使用了java.util.Date。我怎樣才能得到日期以可讀的形式打印? (例如MM/DD/YYYY)?Spring數據休息中的java.util.Date

@Entity 
public class MyEntity{ 
... 

@Column(name="A_DATE_COLUMN") 
@DateTimeFormat(iso=ISO.DATE) 
private Date aDate; 

..getters and setters 

} 

但是當我打印我的實體(覆蓋的toString之後),我一直都想與日期爲長。看起來@DateTimeFormat不會改變行爲。我也嘗試了不同的iso格式,這也沒有幫助。

"aDate" : 1320130800000 

這裏是我的休息春季數據

<dependency> 
      <groupId>org.springframework.data</groupId> 
      <artifactId>spring-data-rest-webmvc</artifactId> 
      <version>1.0.0.RELEASE</version> 
      <exclusions> 
       <exclusion> 
        <groupId></groupId> 
        <artifactId>slf4j-log4j12</artifactId> 
       </exclusion> 
       <exclusion> 
        <artifactId>commons-logging</artifactId> 
        <groupId>commons-logging</groupId> 
       </exclusion> 
      </exclusions> 
     </dependency> 

       <dependency> 
      <groupId>joda-time</groupId> 
      <artifactId>joda-time</artifactId> 
      <version>2.1</version> 
     </dependency> 

任何幫助是非常appeciated POM文件條目。 PS。這裏是執行的toString

@Override 
    public String toString() { 
     return getClass().getName() + "{"+ 
       "\n\taDate: " + aDate 
             + "\n}"; 
    } 
+0

可以請你分享一下toString的實現嗎? – Patton

+0

@Patton,請在編輯時檢查我的toString實現。 – javarebel

+0

而不是使用@DateTimeFormat,我建議你嘗試使用'@Temporal(TemporalType.TIMESTAMP)'http://docs.oracle.com/javaee/6/api/javax/persistence/Temporal.html – Patton

回答

4

樣子你會需要編寫自定義序列,使傑克遜(引擎蓋下的JSON庫Spring使用)正確序列化的日期出來的文字。

你吸氣,然後將看起來像這樣(其中JsonDateSerializer是自定義類)

@JsonSerialize(using=JsonDateSerializer.class) 
public Date getDate() {  
    return date; 
} 

退房this blog post包括用於串行代碼。序列化程序代碼在這裏被複制,但博客文章中的解釋可能會有所幫助。

/** 
* Used to serialize Java.util.Date, which is not a common JSON 
* type, so we have to create a custom serialize method;. 
*/ 
@Component 
public class JsonDateSerializer extends JsonSerializer<Date>{ 

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

    @Override 
    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) 
      throws IOException, JsonProcessingException { 

     String formattedDate = dateFormat.format(date); 

     gen.writeString(formattedDate); 
    } 
} 
+0

的方式對其進行格式化謝謝彼得日,我要去嘗試博客文章中的代碼。我很樂觀,它會工作。 – javarebel

+0

彼得 - 它的工作。這非常快,非常感謝!我已將您的答案標記爲「已接受」。多謝。 – javarebel

+0

根據javadocs:「日期格式不同步,建議爲每個線程創建單獨的格式實例,如果多個線程同時訪問一個格式,它必須在外部同步。」正因爲如此,我建議你實例化一個新的SimpleDateFormat serialize方法裏面,或者同步訪問格式的方法。 – Jay

相關問題