Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON-B REST payload validation

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?

like image 743
voccoeisuoi Avatar asked Nov 08 '22 07:11

voccoeisuoi


1 Answers

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.

like image 138
Andy Guibert Avatar answered Nov 15 '22 07:11

Andy Guibert