users@jersey.java.net

customizing JSON rendering in Jersey

From: Arul Dhesiaseelan <arul_at_fluxcorp.com>
Date: Mon, 28 Apr 2008 18:46:23 -0600

Hi,

I would like to customize JSON rendering in Jersey. Here is my resource
class and associated JAXB classes.

CustomerResource.java

@Singleton
@Path("/customers")
public class CustomerResource {

private static Map<Long, Customer> customers = new
ConcurrentHashMap<Long, Customer>();

  @GET @Path("/list")
  @ProduceMime({"application/json"})
  public Customers getCustomers() throws IOException {
    Customers c = new Customers();
    c.setCustomers(customers.values());
    return c;
  }

}
Customers.java

@XmlRootElement
public class Customers {
  private Collection<Customer> customers;

  public Collection<Customer> getCustomers() {
      return customers;
  }

  public void setCustomers(Collection<Customer> c) {
      this.customers = c;
  }
}

Customer.java
@XmlRootElement(name = "customer")
public class Customer {
  private Long id;
  private String name;
//getters and setters
}

When I access the "/customers/list" URL, I get the following JSON response.

{"customers":{"customers":[{"id":"2","name":"Test2"},{"id":"1","name":"Test1"}]}}

I am not sure why the customers tag is listed twice. I would like to
generate something like

{"customers":[{"id":"2","name":"Test2"},{"id":"1","name":"Test1"}]}

How do I customize JSON rendering in Jersey?

Please clarify.

Thank you,
Arul