Adam Bien's Weblog

JAX-RS: Returning A List Of Instances, Problem and Solution

Wrapping a list of instances with a Response:


    @GET
    public Response workshops() {
        List<Workshop> workshops = ...//a list of entities
        return Response.ok(workshops).build();
    }


Leads to a type loss carried by the Collection and the following (or similar) exception:


MessageBodyWriter not found for media type=application/json, type=class java.util.Arrays$ArrayList, 
genericType=class java.util.Arrays$ArrayList

JAX-RS comes with GenericEntity which carries the generic type. You only have to wrap the Collection with the GenericEntity to solve the problem:


import javax.ws.rs.core.GenericEntity;
//...
  @GET
    public Response workshops() {
        List<Workshop> workshops = ...//a list of entities
        GenericEntity<List<Workshop>> l
        ist = new GenericEntity<List<Workshop>>(workshops) {
        };
        return Response.ok(list).build();
    }

See you at Java EE Workshops at Munich Airport, particularly at: Effective Java EE 7!


NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Nice tips. You can also use Jackson (in Jersey you have to register JacksonFeature) and Collections are managed without wrapping

Posted by Frederic Renout on October 24, 2014 at 07:11 AM CEST #

If you use this way with Jersey, the generated WADL does not include the type information. It will just say something like <representation mediaType="application/json"/>

Which, I guess, is an improvement, because without the GenericEntity, Jersey generates an incorrect mapping which ignores that it's supposed to be a collection:

<response><ns2:representation element="fooItem" mediaType="application/json"/></response>

If you then use this generated WADL to generated a JAXWS client, well, all of your bindings end up being invalid.

Posted by Nim on June 07, 2015 at 11:43 AM CEST #

Thanks Bro, this solve my problem.

Posted by 114.143.6.98 on March 03, 2016 at 07:52 PM CET #

O my god you are my savior! Thanku thanku thanku

Posted by manu on March 26, 2016 at 08:29 PM CET #

WOW, thanks bro ! you save my life.

Posted by kien tran on April 18, 2016 at 05:18 PM CEST #

thanks.. this was awesome..

Posted by anil on August 19, 2016 at 09:05 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License