I have the following GenericRest class which I use to extend rest classes which are based on Entity classes annotated with @XmlRootElement.
public class GenericRest<T extends BaseEntity> {
@Inject @Service
GenericService<T> service;
public GenericService<T> getService() {
return service;
}
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getAll() {
// This works for JSON but does not work for XML Requests.
List<T> list = getService().findAll();
// This just gives the attributes for the BaseEntity.
//GenericEntity<List<T>> list = new GenericEntity<List<T>>(getService().findAll()) {};
return Response.ok(list).build();
}
}
The APPLICATION_JSON
is working fine in the currently uncommented situation, but the APPLICATION_XML
give the error:
Could not find MessageBodyWriter for response object of type: java.util.ArrayList of media type: application/xml
The commented situation works fine for both MediaTypes, but returns just the attributes of the BaseEntity
, not the added attributes for the extended classes. How can I get the attributes for the extended classes and have both MediaTypes working?
Complete repository can be found here (work in progress): https://github.com/martijnburger/multitenant
=== Update 1 ===
I changed the @XmlSeeAlso
annotation on the Entities. It was on the specific entities, but needed to be on the BaseEntity
. Further I used the GenericList
implementation above. This gives correct XML
responses. However, it still returns only the BaseEntity
attributes in JSON
repsonses. I have two followup questions:
- How to return a
JSON
response including the attributes for the specific object that is requested? - I would prefer it if the
BaseEntity
does not have to be touched when adding or removing specificEntity
classes. Because the@XmlSeeAlso
annotation every time I add a newEntity
class, I need to update the annotation. Is there another method to implement this where I do not need to touch theBaseEntity
?
Repository with changes can be found here: https://github.com/martijnburger/multitenant/tree/so_36291250
=== Update 2 ===
I had good hope that the @JsonSubTypes
annotation from Jackson would solve my problem 1. However, it did not. I updated the repository with the Jackson annotations, but I cannot see any changes in the result.
=== Update 3 ===
Please ignore my Update 2. It totally works when using Jackson 2 instead of Jackson 1. Beginners mistake. :( Which leaves me with the question: Is it possible to get this working without touching the BaseEntity every time you add an entity.