Marshal/Un marshal List objects in Jersey JAX-RS using JAXB

▼魔方 西西 提交于 2019-12-03 09:07:51
Paul Samsotha

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>>(){});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!