Anand
Anand

Reputation: 21320

Sending List of objects to Rest service in Java

I have a rest api that looks like this

    @POST
    @Path("/cities")
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response createCity(City city) {
    }

Above is working fine.Now I want to have another service that accepts List of Cities. Then I created a wrapper object which has List of cities field, something like this

 @XmlRootElement
    public class CityHolder {

        List<City> cities;
      ....................

   @POST
    @Path("/cities/list")
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response createCities(CityHolder cityHolder) {
    }

Above worked fine for me. I tried below also

        @POST
        @Path("/cities/list")
        @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
        public Response createCities(List<City> cityList) {
        }

which works fine as well. Can someone let me know what's the best practice to send the list of objects.

Upvotes: 0

Views: 2708

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

I would say if you only want to send the list, use a list of objects. If you want to send additional hints with the list, use a wrapped object.

In your case, I would prefer the list ifself.

Hope it helps, Thierry

Upvotes: 1

Related Questions