Java Reference
In-Depth Information
Marshaling a Custom Type to XML in a Response
Problem
You want your service to provide an XML view of a custom Java type you've defined.
Solution
Use JAXB annotations on your custom type, and let JAX-RS handle the rest. JAX-RS requires
that vendors support certain built-in marshalers, and JAXB is one of them. All you have to do
is annotate the class you want to return as XML with @XmlRootElement , and create a JAX-
RS service that indicates that it produces XML with the @Produces("application/xml")
annotation.
Discussion
Example 8-11 shows a basic Java type that your service can automatically marshal to XML
using JAXB.
Example8-11.Employee.java with JAXB annotations to assist in automatic marshaling
package com.soacookbook.rest.xml;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="employee")
public class Employee {
@XmlElement(name="id")
int id;
@XmlElement(name="name")
String name;
}
This class is just a regular POJO that might as well be a product or line item or some other
type. The only thing that matters here is that the class itself is annotated with @XmlRootEle-
ment to indicate that instances of this class can be marshaled into XML as complete docu-
ments. The fields feature the related @XmlElement annotation to allow them to customize their
names in the resulting XML elements.
Search WWH ::




Custom Search