How to catch a @JsonFormat exception in spring and handle it gracefully to process the payload?

时间秒杀一切 提交于 2021-01-29 05:18:08

问题


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

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date date;

回答1:


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
}

You could also add @JsonIgnoreProperties(ignoreUnknown = true) over your class if you know that its value is not necessary always.



来源:https://stackoverflow.com/questions/55137143/how-to-catch-a-jsonformat-exception-in-spring-and-handle-it-gracefully-to-proce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!