I've developed a Java REST service using JSON-B to map the incoming payload to a POJO.
Now what I'd like to do is to validate the incoming payload, possibly against a JSON schema, but I haven't been able to find anything in this sense so far...
Is it possible to override the default JSON-B mapping process, hence catching any mapping exception and handling it on my own?
To accomplish this you could register your own JAX-RS provider that does the JSON (de)serialization and handle any errors there.
For example:
@Consumes({ "*/*" })
@Provider
public class JsonBProvider implements MessageBodyReader<Object> {
private static final Jsonb jsonb = JsonbBuilder.create();
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations,
MediaType mediaType) {
return true;
}
@Override
public Object readFrom(Class<Object> clazz, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream)
throws IOException, WebApplicationException {
try {
return this.jsonb.fromJson(entityStream, clazz);
} catch (Exception e) {
// Do your custom handling here
}
}
}
This will override the deserialization that occurs through JAX-RS and JSON-B.
NOTE: If you want to do the same thing for serialization as well, you can implement MessageBodyWriter<Object>
in a similar fashion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With