gpt4 book ai didi

Spring Data Rest 中的 java.util.Date

转载 作者:行者123 更新时间:2023-11-30 07:19:56 25 4
gpt4 key购买 nike

我在 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

这是我的 spring 数据 rest 的 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>

非常感谢任何帮助。附言。这是 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;
}

查看 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);
}
}

关于Spring Data Rest 中的 java.util.Date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14323139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com