users@jersey.java.net

Collection serialization in RESTful service

From: Florian Rosenberg <florian_at_vitalab.tuwien.ac.at>
Date: Mon, 22 Oct 2007 10:35:06 -0400 (EDT)

hi folks,

just found out about Jersey and I tried to hack my first example, it works
great except some detail which I do not get to work.

I want to create a RESTful service that implements a simple customer
management where with the following operations in my CustomerResource
class (I left out the impl for readability):

@UriTemplate("/")
public class CustomerService {

  @UriTemplate("customers/{id}")
  @HttpMethod("POST")
  public void addCustomer(@UriParam("id") String id, Customer data) { }

  @UriTemplate("customers/{id}")
  @HttpMethod("DELETE")
  public Customer deleteCustomer(@UriParam("id") String id) { }

  @UriTemplate("customers/{id}")
  @HttpMethod("GET")
  @ProduceMime("text/xml")
  public Customer findCustomer(@UriParam("id") String id) { }

  @HttpMethod("GET")
  @ProduceMime("text/xml")
  @UriTemplate("customers")
  public Collection<Customer> findAllCustomers() { }

  @UriTemplate("customers/{id}")
  @HttpMethod("PUT")
  public void updateCustomer(@UriParam("id") String id, Customer data) { }

}

The Customer class is annotated with JAXB annotations. The above works
great except the "findAllCustomers" as HTTP GET method. The problem is
that Jersey does not know how to serialize a collection of customer
objects. Is there a way to tell Jersey to do that. I tried for hours, the
only workaround is the create your own Collection class that has the
XmlRootElement annotation. But this cannot be the way to go, I guess.

The result of the "findAllCustomer" should be something like:

<customers>
  <customer id="1">
    <!-- ... -->
  </customer>
  <customer id="2">
    <!-- ... -->
  </customer>
</customers>

Any help is appreciated.

Thanks,
-Florian