如何在Spring中捕获@JsonFormat异常并优雅地处理它以处理有效负载? [英] How to catch a @JsonFormat exception in spring and handle it gracefully to process the payload?
问题描述
我有一个spring应用程序,其中使用@JsonFormat
批注反序列化日期格式.但是,当我发送一个元素数组时,即使其中一个条目的日期无效,我的整个有效负载也会失败.
I have a spring app in which I am using the @JsonFormat
annotation to deserialize a date format. But when I sent an array of elements my entire payload fails even if one of the entries have an invalid date.
是否可以通过优雅地处理此异常来解决此问题,方法是用默认值替换失败的日期或忽略该数组条目.
Is there a way I can surpass this by gracefully handling this exception, by either replacing the failed date with a default value or ignoring that array entry.
jackson.version:2.7.5
,
spring.version:5.0.0.RELEASE
jackson.version: 2.7.5
,
spring.version: 5.0.0.RELEASE
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date date;
推荐答案
您可以编写自定义解串器为您的班级设置了默认值,以防出现问题.像这样:
You could write a custom deserializer for your class where you set a default value in case something goes wrong. Something like:
public class MyJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
return new Date();
}
}
}
然后在您的课堂上,您可以执行以下操作:
Then on your class you could do something like:
class MyClass {
//...Fields
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
@JsonDeserialize(using = MyJsonDateDeserializer.class)
private Date date;
//...Fields
}
如果您知道不一定总是需要它的值,也可以在类上添加@JsonIgnoreProperties(ignoreUnknown = true)
.
You could also add @JsonIgnoreProperties(ignoreUnknown = true)
over your class if you know that its value is not necessary always.
这篇关于如何在Spring中捕获@JsonFormat异常并优雅地处理它以处理有效负载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!