SpringBoot前後端分離Instant時間戳自定義解析
阿新 • • 發佈:2018-11-27
在SpringBoot專案中,前後端規定傳遞時間使用時間戳(精度ms).
@Data public class Incident { @ApiModelProperty(value = "故障ID", example = "1") private Integer id; @ApiModelProperty(value = "故障產生時間", allowEmptyValue = true) private Instant createdTime; @ApiModelProperty(value = "故障恢復時間", allowEmptyValue = true) private Instant recoveryTime; }
以上為簡略實體類定義.
@Transactional(rollbackFor = Exception.class) @PostMapping(path = "/incident") public void AddIncident(@Valid @RequestBody Incident incident) { incident.setBusinessId(0); if (1 != incidentService.addIncident(incident)) { throw new Exception("..."); } }
在實際使用過程中,發現Incident
中的createdTime
以及recoveryTime
數值不對.
排查故障,前端去除時間戳後三位(即ms數),則時間基本吻合.
因此,可以確定是SpringBoot
在轉換Instant
時使用Second
進行轉換.
因此對於Instant
型別的轉換新增自定義解析(SpringBoot
使用com.fasterxml.jackson
解析資料).
public class InstantJacksonDeserialize extends JsonDeserializer<Instant> { @Override public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { String text = jsonParser.getText(); Long aLong = Long.valueOf(text); Instant res = Instant.ofEpochMilli(aLong); return res; } }
在涉及到Instant
的屬性上加上相應註解,程式碼具體如下:
@Data
public class Incident {
@ApiModelProperty(value = "故障ID", example = "1")
private Integer id;
@JsonDeserialize(using = InstantJacksonDeserialize.class)
@ApiModelProperty(value = "故障產生時間", allowEmptyValue = true)
private Instant createdTime;
@JsonDeserialize(using = InstantJacksonDeserialize.class)
@ApiModelProperty(value = "故障恢復時間", allowEmptyValue = true)
private Instant recoveryTime;
}
添加註解後,Instant
物件能夠按照ms
精度進行解析.
PS:
如果您覺得我的文章對您有幫助,可以掃碼領取下紅包,謝謝!