java - 是否可以将 JsonFormat 日期时间的某些部分设为可选?
问题描述
我有一个用秒部分定义的字段(即:“ss”),如下所示
@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")
private Date date;
是否可以将秒部分设为可选?以便以下日期字符串都可以工作:
- “2020-02-13T16:02:11 EST”将被解析为“Thu Feb 13 16:02:11 EST 2020”
- “2020-02-13T16:02 EST”将被解析为“Thu Feb 13 16:02 EST 2020”
我正在考虑类似的事情(但这不起作用......):“yyyy-MM-dd'T'HH:mm[:ss] z”
谢谢。
解决方案
我得到了答案。
- 添加一个客户化的反序列化器类“DateDeserializer.class”
- DateDeserializer.class 实现了有和没有第二部分的模式。
附上代码示例:
@JsonDeserialize(using = DateDeserializer.class)
@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")
public class DateDeserializer extends StdDeserializer<Date> {
private static final SimpleDateFormat withSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z");
private static final SimpleDateFormat withoutSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm z");
public DateDeserializer() {
this(null);
}
public DateDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String dateString = p.getText();
if (dateString.isEmpty()) {
//handle empty strings however you want,
//but I am setting the Date objects null
return null;
}
try {
return withSeconds.parse(dateString);
} catch (ParseException e) {
try {
return withoutSeconds.parse(dateString);
} catch (ParseException e1) {
throw new RuntimeException("Unable to parse date", e1);
}
}
}
}
推荐阅读
- apache - Prestashop 1.7 无法访问 api
- javascript - jquery ui 选项卡将 display:none 添加到 iframe
- excel - VBA:如何获得(更多)动态文件名?
- html - 使用它的参数转到一个链接?
- android - 如何解决错误“执行命令 react-native run-android 时无法找到请求目标的有效认证路径”
- java - 程序使用字节流来执行 8 位字节的输入和输出
- h5py - 使用类型“8 位整数 (80) 数组”将字符串保存到 h5py 数据集
- microsoft-edge - 如何将响应标头属性设置为重定向(302)请求
- ionic-framework - 离子刷新器背景颜色不会改变离子
- python - 从 dict 制作 pandas 数据框