If you want to return both XML and JSON objects, you can
reuse the same method with minimal modification. You must
specify "application/xml", "application/json",
and "text/xml" in the @Produces annotation.
The following example illustrates a simple JSON return method that
returns a BookList object for the BookList JAXB
class:package com.example.jaxrs;
@GET
@Produces("application/json", "application/xml", "text/xml")
public BookList getBookList() {
BookList list = /* get a book list */
return list;
}
The following example illustrates a simple JSON return
method that returns a javax.ws.rs.core.Response object
for the BookList JAXB class:@GET
@Produces("application/json", "application/xml", "text/xml")
public javax.ws.rs.core.Response getBookList() {
BookList list = /* get a book list */
return Response.ok(list).build();
}
Content negotiation through the Accept HTTP header of
the client request determines whether a JSON or XML representation
is returned by the resource method. Read about content negotiation
for more information. By reusing the JAXB annotated objects, you can
shorten the development time to serve both JSON and XML from the same
code. Reusing the same model code can be beneficial if specific JSON
or XML formatted output is not required.If you require specific
XML and JSON output and cannot reuse the same JAXB annotated classes,
one way to solve the problem is to use two different resource methods.
The JSON resource method must be annotated with an @Produces("application/json") annotation
and the XML resource method must be annotated with an @Produces("application/xml",
"text/xml") annotation.