How can this resource method produce json
or xml
results ?
Should I parse the request accept header and make an if/else
branch, or jersey will do that
for me ?
@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
...
}
An example of how doGetAsXmlOrJson()
may implemented will nice.
As this Java EE tutorial states
The @Produces annotation is used to specify the MIME media types or representations a resource can produce and send back to the client.
so it doesn't actually tell JAX-RS to produce two content types in the response. It initially acts as an indicator for determining which handler method to use. If you had two GET
s for the same path, the @Produces
would help choosing the most appropriate.
In your cast, the method can produce both content type. Which one it eventually produces depends on the Accept
header in the request.
From the same tutorial
If a resource class is capable of producing more that one MIME media type, the resource method chosen will correspond to the most acceptable media type as declared by the client. More specifically, the Accept header of the HTTP request declared what is most acceptable.
The fact that you are returning a String
kind of shows that it's up to your implementation to produce the right content. If instead you returned a Pojo of some sort, I do believe Jersey would use the appropriate conversion tool to produce XML (maybe with JAXB) or JSON (maybe with Jackson).