Java Reference
In-Depth Information
Customer customer
=
new
new
Customer
();
customer
.
setId
(
42
);
customer
.
setName
(
"Bill Burke"
);
JAXBContext ctx
=
JAXBContext
.
newInstance
(
Customer
.
class
);
StringWriter writer
=
new
new
StringWriter
();
ctx
.
createMarshaller
().
marshal
(
customer
,
writer
);
String custString
=
writer
.
toString
();
customer
= (
Customer
)
ctx
.
createUnmarshaller
()
.
unmarshal
(
new
new
StringReader
(
custString
));
We first create an initialized instance of a
Customer
class. We then initialize a
JAXBContext
to understand how to deal with
Customer
classes. We use a
Marshaller
instance created by
the method
JAXBContext.createMarshaller()
to write the
Customer
object into a Java
string. Next we use the
Unmarshaller
created by the
JAXBCon-
text.createUnmarshaller()
method to re-create the
Customer
object with the XML
string we just created.
Now that we have a general idea of how JAXB works, let's look at how JAX-RS integrates
with it.
JAXB JAX-RS Handlers
The JAX-RS specification requires implementations to automatically support the marshalling
and unmarshalling of classes that are annotated with
@XmlRootElement
or
@XmlType
as well
as objects wrapped inside
javax.xml.bind.JAXBElement
instances. Here's an example that
interacts using the
Customer
class defined earlier:
@Path
(
"/customers"
)
public
public class
class
CustomerResource
CustomerResource
{
@GET
@Path
(
"{id}"
)
@Produces
(
"application/xml"
)
public
public
Customer
getCustomer
(
@PathParam
(
"id"
)
int
int
id
) {
Customer cust
=
findCustomer
(
id
);
return
return
cust
;
}
@POST