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

后端 未结 1 514
遇见更好的自我
遇见更好的自我 2021-02-11 08:35

Good Morning. Today morning when I am going through Jersey Entity providers MessageBodyReaders and MessageBodyWriters I came across the following probl

相关标签:
1条回答
  • 2021-02-11 09:01

    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>>(){});
    
    0 讨论(0)
提交回复
热议问题