Fork me on GitHub

Programming, Internet & more

Jersey Client – Retrieve list of entitites

One of the tricky things when you use a jersey client to consume RESTful services, is to retrieve a list of entities instead of a single one.

Assume you have the following entity:

import javax.xml.bind.annotation.XmlRootElement;

public class Person {

    private String name;

    public String getName() {
        return name;

    public void setName(String name) { = name;

Your RESTful service is able to populate a list of Person entities and looks like this:

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;

public class PersonResource {

    public List<Person> getPersons() {
        List<Person> list = new ArrayList<Person>();
        //fill list
        return list;

With jersey the creation of a REST client is very easy. It’s almost pretty straight forward, although it can become tricky if you want to retrieve a list of entities.
Look at the following example:

import java.util.List;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;

public class PersonClient {

    public void getPersons() {
        List<Person> list = Client.create().resource("http://localhost:8080/myapplication/rest/persons/")
                .get(List<Person>); //won't compile

              //use GenericType instead
        List<Person> list = Client.create().resource("http://localhost:8080/myapplication/rest/persons/")
                .get(new GenericType<List<Person>>(){});

The first line in the method won’t compile. The trick is to use the class GenericType together with Generics to retrieve a list of Person entities.

Category: programming

Leave a Reply

Your email address will not be published. Required fields are marked *