如何在ISO格式中返回Date对象而不是Java中的时间戳?

时间:2016-01-08 18:41:01

标签: java json date spring-boot

假设有一个java类

public class User(){
    String name;
    Date dateCreated;
}

和一个Spring启动控制器:

@RequestMapping(value = "getUser", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE))
public User getUser() {
   User newUser = new User();
   newUser.dateCreated = new Date();
   return newUser;
}

如果我有一个以JSON格式返回该User对象的rest API端点,如上所述,dateCreated将以时间戳格式而不是ISO格式发送。有没有办法让Java以Iso格式返回日期,而不必指定一个以Date作为字符串的新返回对象?

执行此操作的一种方法是将日期转换为字符串并发送,但我想知道是否有更方便的方式..

1 个答案:

答案 0 :(得分:9)

使用以下内容更新您的application.properties:

spring.jackson.serialization.write-dates-as-timestamps:false

现在您可以按如下方式在bean中指定格式:

public class User(){
    String name;
    @JsonFormat(pattern="yyyy-MM-dd")
    Date dateCreated;
}