I have a JAX-RS 2.0 service that must return a list of objects of unknown type. Moreover, I want that this list be nested in a wrapper object. So, for example, I would like to produce this output:
{ "objects": [ {"name":"goofy"}, {"name":"mickey"} ] }
If the objects' type were known, this is an easy task. I have tried in many ways, including using GenericEntity, however I cannot find a solution.
I am using WAS Glassfish 4.1, however I would like the solution were independent from specific WAS.
This is the relevant piece of code of the service:
@GET
@Path("{entity}")
public Response find(@PathParam("entity") String entity) {
Class clazz = someMethod(entity);
List list = someMethod(clazz); //return a list of object of clazz
WrapperClass wrapper = new WrapperClass();
wrapper.setObjects(list);
return Response.ok().entity(wrapper).build();
}
This code produces as output:
{ "objects": [ "object goofy", "object mickey" ] }
i.e. the objects are not serialized properly.
With Glassfish 4, the default JSON provider is MOXy which is built on top of JAXB. With JAXB, the entity types need to be known beforehand. So the result you are getting is just the value of toString()
, which is the behavior when the type is not know.
If you want to switch over to using Jackson as the JSON provider, it should work. Jackson does not need to know the type beforehand as it just introspects all the bean properties. To use Jackson in Glassfish, you need to add the dependency to your project and register the JackonFeature
with the application.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
<scope>provided</scope>
</dependency>