在我的对象中有以下声明:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX")
private ZonedDateTime start;当我解析像2016-12-08T12:16:07.124Z (使用Jackson Json De serilaizer)这样的时间戳时,它工作得很好,但是一旦我收到没有毫秒的时间戳(比如"2016-12-08T12:16:07Z"),它就会抛出异常。
我如何才能使毫秒的格式规范可选?
发布于 2016-12-08 10:52:39
如果使用的是Java 8,请尝试在方括号内指定.SSS ( [.SSS] )
JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS]X")发布于 2020-03-05 14:10:23
如果millis由1、2或3位数字组成,则可以使用此模式。
JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS][.SS][.S]X")可选区段命令严格
发布于 2018-03-19 20:35:39
对于那些无法让[.SSS]解决方案工作的人,下面是我最后所做的事情。
将@JsonFormat注释保留在您的字段中进行序列化,但是构建一个用于解析日期的自定义反序列化器,它可能没有指定毫秒部分。一旦实现了反序列化器,就必须将其注册为ObjectMapper作为SimpleModule。
class DateDeserializer extends StdDeserializer<Date> {
private static final SimpleDateFormat withMillis = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
private static final SimpleDateFormat withoutMillis = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
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 withMillis.parse(dateString);
} catch (ParseException e) {
try {
return withoutMillis.parse(dateString);
} catch (ParseException e1) {
throw new RuntimeException("Unable to parse date", e1);
}
}
}
}现在您有了一个自定义反序列化器,剩下的就是注册它。我使用的是我在项目中已经拥有的ContextResolver<ObjectMapper>,但是您使用ObjectMapper应该是可以的。
@Provider
class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
mapper = new ObjectMapper();
SimpleModule dateModule = new SimpleModule();
dateModule.addDeserializer(Date.class, new DateDeserializer());
mapper.registerModule(dateModule);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}https://stackoverflow.com/questions/41037243
复制相似问题