在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;
}
}
public class InstantJacksonSerializer extends JsonSerializer<Instant> {
@Override
public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(instant.toEpochMilli());
}
}
在涉及到Instant
的属性上加上相应注解,代码具体如下:
@Data
public class Incident {
@ApiModelProperty(value = "故障ID", example = "1")
private Integer id;
@JsonSerialize(using = InstantJacksonSerializer.class)
@JsonDeserialize(using = InstantJacksonDeserialize.class)
@ApiModelProperty(value = "故障产生时间", allowEmptyValue = true)
private Instant createdTime;
@JsonSerialize(using = InstantJacksonSerializer.class)
@JsonDeserialize(using = InstantJacksonDeserialize.class)
@ApiModelProperty(value = "故障恢复时间", allowEmptyValue = true)
private Instant recoveryTime;
}
添加注解后,Instant
对象能够按照ms
精度进行解析.
https://www.cnblogs.com/jason1990/p/10028262.html
标签:
SpringBoot基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2017-12-18 查找 TextBox 对象中非法数据的示例