Java Reference
In-Depth Information
return ctx ;
} else
return
else {
return
return null
null ;
}
}
}
Your resolver class must implement ContextResolver with the parameterized type of
JAXBContext . The class must also be annotated with the @javax.ws.rs.ext.Provider an-
notation to identify it as a JAX-RS component. In our example, the CustomerResolver con-
structor initializes a JAXBContext specific to our Customer class.
You register your ContextResolver using the javax.ws.rs.core.Application API dis-
cussed in Chapters 3 and 14 . The built-in JAXB handler will see if there are any registered
ContextResolvers that can create JAXBContext instances. It will iterate through them, call-
ing the getContext() method passing in the Java type it wants a JAXBContext created for.
If the getContext() method returns null , it will go on to the next ContextResolver in the
list. If the getContext() method returns an instance, it will use that JAXBContext to handle
the request. If there are no ContextResolvers found, it will create and manage its own
JAXBContext . In our example, the CustomerResolver.getContext() method checks to see
if the type is a Customer class. If it is, it returns the JAXBContext we initialized in the con-
structor; otherwise, it returns null .
The @Produces annotation on your CustomerResolver implementation is optional. It allows
you to specialize a ContextResolver for a specific media type. You'll see in the next section
that you can use JAXB to output to formats other than XML. This is a way to create
JAXBContext instances for each individual media type in your system.
JAXB and JSON
JAXB is flexible enough to support formats other than XML. The Jettison [ 5 ] open source
project has written a JAXB adapter that can input and output the JSON format. JSON is a
text-based format that can be directly interpreted by JavaScript. It is the preferred exchange
format for Ajax applications. Although not required by the JAX-RS specification, many
JAX-RS implementations use Jettison to support marshalling JAXB annotated classes to and
from JSON.
JSON is a much simpler format than XML. Objects are enclosed in curly brackets, “{}”, and
contain key/value pairs. Values can be quoted strings, Booleans (true or false), numeric val-
ues, or arrays of these simple types. Here's an example:
 
Search WWH ::




Custom Search