I am creating a web service with JAX-RS. I know you can annotate the domain model with JAXB annotations and lean back and watch the whole class being transformed to XML/JSON. However, this is not suitable for all scenarios in my application. It is not always appropriate that the class is marshalled to XML. Sometimes I only need some fields etc, and I also want to be able to add custom elements on the fly which is not represented in the domain model.
How would you do that? Do I need to use other frameworks for this? I just found GSON, is that worth looking at? XML representation of my resources is not that important. If I am using GSON, what should the web service respond with? Do you just use String as return type then?
Pseudocode, haven’t looked at GSON yet.
@Produce("application/json")
public String someMethod() {
return gson.toJSON();
}
In a case where you have multi-variant response types its often best to use javax.ws.rs.core.Response as the return. This gives you full control, at run time, of determining the actual entity that will be wrapped and returned.
You can then, when your resource method is invoked, decide to either return the core business object, or a wrapper around the business object, or a custom serialized version (as a String). Rough pseudocode:
One advantage of this approach is that server side interceptors will still fire and perform translations on your entity objects, so that you can still take advantage of on-the-fly serialization to JSON and XML, but at the same time you can circumvent the translation, by using a String as the entity type.