You can process JavaScript Object
Notation (JSON) requests and responses with Java™ Architecture for XML Binding (JAXB) annotated
objects and Jackson. Jackson is the default JSON processor in WebSphere® Application Server.
By default, it is included in the JAX-RS runtime environment so you
do not need to configure Jackson.
About this task
This task provides instructions for processing JSON requests
and responses with JAXB annotated objects and Jackson.
Procedure
- Create a resource method.
For the resource method
to return JSON content, return an instance of a JAXB class directly
or return a
javax.ws.rs.core.Response
object with
a JAXB object as the response entity. You must also either add an
@Produces("application/json")
annotation,
or set the Content-Type header in your Response object to be
"application/json"
.
The following example illustrates simple JSON return methods for the
BookList
JAXB
class:
@GET
@Produces("application/json")
public BookList getBookList() {
BookList list = /* get a book list */
return list;
}
or
@GET
@Produces("application/json")
public javax.ws.rs.core.Response getBookList() {
BookList list = /* get a book list */
return Response.ok(list).type(MediaType.APPLICATION_JSON_TYPE).build();
}
- 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:
@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 client request's Accept HTTP header helps determine 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.
Results
You have returned a JSON representation with JAXB annotated
classes through the Jackson JSON processor.