javaGirl
javaGirl

Reputation: 195

Java Rest - send parametrized List using GET method

I am trying to send a List by GET method.

Here is my Server side:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers(){
    return managment.getUsers();
}

And my client side:

public static void getUsers(){
    try {
        ClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        Client client = Client.create(clientConfig);




        WebResource webResource = client
                .resource("http://localhost:8080/Serwer07/user");

        ClientResponse response = webResource.accept("application/json")
                .get(ClientResponse.class);

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }

       List users = response.getEntity(List.class);          
       User user = (User) users.get(0);  //cannot cast
        e.printStackTrace();
    }
}

I have problem with cast from Java Object to User. How can I send this List ?

Thanks in advance.

Upvotes: 5

Views: 2084

Answers (1)

Anthony Accioly
Anthony Accioly

Reputation: 22481

Use GenericType.

List<User> users = webResource.accept(MediaType.APPLICATION_JSON)
   .get(new GenericType<List<User>>() {});

UPDATE

ClientResponse also overloads getEntity to accept GenericTypes.

List<User> users = response.getEntity(new GenericType<List<User>>() {});      

Upvotes: 5

Related Questions