users@jersey.java.net

[Jersey] MessageBodyReader/Writer selection

From: Richard Sand <rsand_at_idfconnect.com>
Date: Sun, 11 Sep 2016 15:05:27 +0000

Hi all -

I know this topic has come up before but I haven't been able to discern
a conclusive answer. I have two MessageBodyReaders, one that handles a
parent type (call it MyBaseClass) and another that handles a more
specific subclass (call it MySubClass), and I'm struggling to find a way
to have Jersey use the reader for the subclass, because the base class
reader is also returning true for isReadable.

                public class MyBaseClassMessageBodyReader<T> implements
MessageBodyReader<JsonDeserializer<T>> {
    public boolean isReadable(Class<?> type, Type genericType,
java.lang.annotation.Annotation[] annotations, MediaType mediaType) {
        return MyBaseClass.class.isAssignableFrom(type);
    }
...
}

public class MySubClassMessageBodyReader<T> implements
MessageBodyReader<JsonDeserializer<T>> {
    public boolean isReadable(Class<?> type, Type genericType,
java.lang.annotation.Annotation[] annotations, MediaType mediaType) {
        return MySubClass.class.isAssignableFrom(type);
    }
...
}

Is there a way I can specify an order-of-evaluation in Jersey so that it
checks MySubClassMessageBodyReader before MyBaseClassMessageBodyReader?

If there is a way, is it only available in Jersey2? We're in the middle
of transitioning from Jersey1 to Jersey2 so we need to come up with
solutions for both, even if the solutions are different.

Best regards,

Richard