Spring Data Rest:日期序列化日期为时间戳

时间:2016-07-24 07:54:56

标签: spring spring-boot spring-data-rest

我使用spring boot和spring数据来构建RESTful API。我想以json响应格式约会为时间戳。目前,我的回答是:

{
  "firstName": "An",
  "lastName": "Nguyen",
  "createdDate": "2016-04-17T03:25:44.000+0000"
}

我期待它:

{
  "firstName": "An",
  "lastName": "Nguyen",
  "createdDate": "1469346389"
}

我该怎么做?什么需要重新配置?

我的模特:

@Entity
@Table(name = "users")
public class User extends AbstractEntity<Long> implements UserDetails {

  @Column(name = "first_name", length = 50)
  private String firstName;

  @Column(name = "last_name", length = 50)
  private String lastName;

  @Column(name = "created_date")
  private Date createdDate = new Date();

  .....
}

我的存储库:

@Transactional
@RestResource(path = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Long>, JpaSpecificationExecutor<User> {

    User findByUsername(@NotNull String username);

}

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

希望这个注释可以帮助你:

@JsonFormat(shape = JsonFormat.Shape.NUMBER)

答案 1 :(得分:1)

您可以自定义Spring Data REST使用的默认ObjectMapper,例如:

@Configuration
public class SpringDataRestConfig extends RepositoryRestConfigurerAdapter {
    @Override
    public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    }
}

答案 2 :(得分:0)

您可以将日期存储为长。这里的帖子就是这样做的。

Properly Utilizing Epoch Seconds with JPA in Spring Boot