Skip to content
Advertisement

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

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;

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement