Carven
Carven

Reputation: 15660

How to throw exception when validating JSON payloads during deserialisation in Jackson?

I'm creating a custom Jackson deserializer class to map a JSON payload to an object. In my deserialize method I did some checks on the JSON payload to see whether any fields are missing or incongruent to the POJO.

I tried throwing exceptions in the deserialize method with something like this:

@Override
public MyObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
   // if some fields are missing throw error:
   throw new MissingFieldsException("name field is missing");
} 

However, I'm not allowed to to throw my own exception in the deserialize method because the method implements a interface which I can only throw IOException and JsonProcessingException:

public abstract T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException;

In this case, how do I do validations of JSON payloads when doing deserialisations?

Upvotes: 2

Views: 1076

Answers (1)

pirho
pirho

Reputation: 12245

To be exact the class JsonProcessingException is not "protected". The constructors for that class are. So you can easily extend that class - as comments suggest - with some public constructor, for example:

@SuppressWarnings("serial")
public static class MyJsonProcessingException extends JsonProcessingException {
    protected MyJsonProcessingException(String msg) {
        super(msg);
    }
}

You can also declare it as anonymous inner class by providing the body with new operator. Like:

throw new JsonProcessingException("Error msg") {};

For this you might also want to add either something like:

private static final long serialVersionUID = 1L;

in the body of above anonymous inner class or add the annotation @SuppressWarnings("serial") to the method where this is thrown, to get rid of warnings about missing serial.

Generally you can also throw any unchecked exception, like RuntimeException itself or like:

@SuppressWarnings("serial")
public static class MyJsonProcessingRuntimeException extends RuntimeException {}

but in case of RuntimeException you need to be more careful in your coding - so be aware that it can be thrown without any declaration - so extending JsonProcessingException is prefereble, IMO.

Upvotes: 1

Related Questions