练习:将从表读出来的时间戳除以1000(java读时间戳会多出3个000)用jackson包 实现

时间:2021-08-19 14:42:12

练习:将从表读出来的时间戳除以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;

}