response . responsebuilder生成java.util.Date作为数字



我使用的是javae -api 6.0。

我有一个带有java.util.Date字段的实体bean,名为updated.

public class Tariff implements Serializable {
    private Date updated

我有一个REST服务。

@GET
@Path("/example")
public Response getTariff() {
    return Response.status(200).entity(new Records(createExampleTariff())).build();
}

当我调用我的REST服务,它返回日期作为一个数字。

{"records":{"description":"OTHER","message":"Nothing to say","status":"OK", "updated":1475822878961},"status":"ok"}

有谁知道我如何在不使用DTO的情况下工作。

原因:

The date is always stored as the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

解决方案:

您可以使用org.codehaus.jackson.map.JsonSerializer转换日期格式。通过用转换逻辑编写一个类JsonDateSerializer

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

你可以在这里得到详细的说明

Date类实际上是一个数字的包装器,该数字是自称为" epoch"的标准基准时间(即1970年1月1日00:00:00 GMT)以来指定的毫秒数。你需要明确你所说的"工作到此为止"是什么意思。要么发送一个数字,要么发送一个字符串。对于字符串,您可以使用SimpleDateFormat来生成您想要的字符串。

我仍然会返回时间戳,所以它仍然很简单。如果你真的需要以人类可读的格式发送日期,你可以创建一个类来扩展org.codehaus.jackson.map.JsonSerializer,并实现你想要的序列化方法。然后像这样注释日期getter

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

查看这篇文章了解更多信息

最新更新