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

后端 未结 1 511
遇见更好的自我
遇见更好的自我 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. -> .

    List list = new ArrayList<>();
    GenericEntity> entity = new GenericEntity>(list) {};
    Response response = Response.ok(entity).build();
    

    For accepting a body in resource method, simply accepting List as an argument is enough. It will accept


    UPDATE

    To retrieve the List on the client side, we should make use of GenericType. Se this post.

    Jersey 1

    WebResource resource = client.resource("...");
    List products = resource.get(new GenericType>(){});
    

    Jersey 2/JAX-RS 2

    Response response = ...
    List products = response.readEntity(new GenericType>(){});
    

    0 讨论(0)
提交回复
热议问题