[英]java.util.Date in Spring Data Rest
我在spring(3.1)數據REST中使用java.util.Date。 如何獲得以人類可讀格式打印的日期? (例如MM / DD / YYYY)?
@Entity
public class MyEntity{
...
@Column(name="A_DATE_COLUMN")
@DateTimeFormat(iso=ISO.DATE)
private Date aDate;
..getters and setters
}
但是,當我打印實體(重寫toString之后)時,我總是將日期弄長。 似乎@DateTimeFormat不會更改行為。 我也嘗試了不同的iso格式,但這都沒有幫助。
"aDate" : 1320130800000
這是我的彈簧數據架的POM文件條目
<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>
非常感謝任何幫助。 PS。 這是toString實現
@Override
public String toString() {
return getClass().getName() + "{"+
"\n\taDate: " + aDate
+ "\n}";
}
看來您需要編寫一個自定義序列化程序才能使Jackson(spring后台使用的JSON庫)將日期正確序列化為文本。
然后,您的getter將如下所示(其中JsonDateSerializer是自定義類)
@JsonSerialize(using=JsonDateSerializer.class)
public Date getDate() {
return date;
}
請查看此博客文章 ,其中包含用於序列化程序的代碼。 此處復制了序列化程序代碼,但博客文章中的解釋可能有所幫助。
/**
* 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.