JAX-RS: Returning A List Of Instances, Problem and Solution 📎
Wrapping a list of instances with a Response
:
@GET
public Response workshops() {
List<Workshop> workshops = ...//a list of entities
return Response.ok(workshops).build();
}
Leads to a type loss carried by the Collection
and the following (or similar) exception:
MessageBodyWriter not found for media type=application/json, type=class java.util.Arrays$ArrayList,
genericType=class java.util.Arrays$ArrayList
JAX-RS comes with GenericEntity which carries the generic type. You only have to wrap the Collection
with the GenericEntity
to solve the problem:
import javax.ws.rs.core.GenericEntity;
//...
@GET
public Response workshops() {
List<Workshop> workshops = ...//a list of entities
GenericEntity<List<Workshop>> l
ist = new GenericEntity<List<Workshop>>(workshops) {
};
return Response.ok(list).build();
}
See you at Java EE Workshops at Munich Airport, particularly at: Effective Java EE 7!