Java – Jersey didn’t see my messagebodyreader
I'm trying to use my own JSON messagebodyreader / messagebodywriter (because I didn't use @ xmlrootelement... Annotation on my domain class)
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public final class MyGsonMessageBodyHandler implements MessageBodyWriter<Object>,MessageBodyReader<Object> {
...
}
Jersey uses this class as a messagebodywriter (because it stops at a breakpoint in the implemented method writeto) Hovewer doesn't see this class as a messagebodyreader (it still refuses to use my messagebodyreader even when I decompose this class into a separate implementation of messagebodyreader / messagebodywriter)
The test code is as follows (Jersey grizzly):
final Greeting greeting = resource.path("/greeting")
.queryParam("name",name)
.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.get(Greeting.class);
I got the following error:
A message body reader for Java class test.Greeting,and Java type class test.Greeting,and MIME media type application/json was not found
I want to know what kind of magic is needed to write my own messagebodyreader?
Solution
After a while, I found the root cause of the problem My messagebodyreader / writer implementation is OK (I work normally with restlet), but if you use jerseytest, please don't forget to add messagebodyreader / writer to its clientconfig:
/**
* Creates custom REST client config which is mandatory since we don't use any JSON providers.
* @return Jersey Client Config with the required classes to read/write in(out)coming data.
*/
private static ClientConfig createClientConfig() {
final ClientConfig config = new DefaultClientConfig();
config.getClasses().add(GsonMessageBodyHandler.class);
config.getClasses().add(GsonAwareContextResolver.class);
return config;
}
/**
* Public ctor
* @throws com.sun.jersey.test.framework.spi.container.TestContainerException On error
*/
public MyRestExposuretest() throws TestContainerException {
super(new WebAppDescriptor.Builder("my.rest.package")
.clientConfig(createClientConfig())
.contextPath("/")
.build());
}
Otherwise, your client code will not be able to read / write to your POJO
