練習:將從表讀出來的時間戳除以1000(java讀時間戳會多出3個000)jackson包 實現
entity
@Entity @DynamicUpdate //自動更新日期 @Data //get/set public class OrderDetail { @Id private String detailId; /**訂單id**/ private String orderId; /**商品id**/ private String productId; /**商品名**/ private String productName; /**商品價格**/ private BigDecimal productPrice; /**購票數量**/ private Integer productQuantity; /**商品圖片**/ private String productIcon; /**時間戳**/ private Date createTimestamp; /**時間戳**/ private Date updateTimestamp; }
java讀出的數據格式,時間戳會精確到毫秒,多出3個000
{ "statusCode": 0, "message": "返回成功", "data": [{ "orderId": "1542785381425923730", "buyerName": "王五", "buyerPhone": "15605852476", "buyerAddr": "北京王府井", "buyerOpenid": "110112", "buyerAmount": 4.40, "orderStatus": 0, "payStatus": 0, "createTimestamp": 1542794276000, "updateTimestamp": 1542794276000, "orderDetailList": null }] }
解決方法:
1.繼承com.fasterxml.jackson.databind.JsonSerializer;的類,並復寫:serialize(T.....)方法
public class DateToTimestamp extends JsonSerializer<Date> { @Override public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeNumber(date.getTime() / 1000); } }
2.在實體類上用上新建的 DateToTimestamp 類的注解
@Entity @DynamicUpdate //自動更新日期 @Data //get/set public class OrderMaster { @Id private String orderId; /**買家名字**/ private String buyerName; /**買家手機**/ private String buyerPhone; /**買家地址**/ private String buyerAddr; /**用戶openid**/ private String buyerOpenid; /**訂單金額**/ private BigDecimal buyerAmount; /**訂單狀態, 默認狀態0新訂單**/ private Integer orderStatus = OrderStatusEnum.NEW.getCode(); /**支付狀態, 默認狀態0等待支付**/ private Integer payStatus = PayStatusEnum.WAIT.getCode(); /** * 此注解表示時間戳除以1000 */ @JsonSerialize(using = DateToTimestamp.class) private Date createTimestamp; /** * 此注解表示時間戳除以1000 */ @JsonSerialize(using = DateToTimestamp.class) private Date updateTimestamp; }