Good Morning. Today morning when I am going through Jersey Entity providers MessageBodyReader
s and MessageBodyWriter
s I came across the following probl
First
You don't need your own MessageBodyWriter/Reader
. Jersey/JAX-RS alread has standard support for this. I would stick with the default, unless you have a really, really good reason for needed to whip up your own.
Second
We don't need the wrapper, you can simple return a GenericEntity. This will automatically wrap the elements in a "plural wrapper" element, i.e. <product>
-> <products>
.
List<Product> list = new ArrayList<>();
GenericEntity<List<String>> entity = new GenericEntity<List<Product>>(list) {};
Response response = Response.ok(entity).build();
For accepting a body in resource method, simply accepting List<Product>
as an argument is enough. It will accept <products><product/><product/></products>
UPDATE
To retrieve the List<Product>
on the client side, we should make use of GenericType
. Se this post.
Jersey 1
WebResource resource = client.resource("...");
List<Product> products = resource.get(new GenericType<List<Product>>(){});
Jersey 2/JAX-RS 2
Response response = ...
List<Product> products = response.readEntity(new GenericType<List<Product>>(){});