我编写了一个简单的提供程序来处理这种情况,它似乎按我的预期工作。它会将 xmlType 包装在一个 jaxbelement 中,以便对其进行编组。
/**
* by default we are unable to write an {@link XmlType} object as xml it must be
* an {@link XmlRootElement} based object this class will wrap {@link XmlType}
* with {@link JAXBElement} and marshall them
*
* @author shaun
*
*/
@Provider
@Consumes({ "application/xml", "text/xml" })
public class XMLTypeWriter extends AbstractRootElementProvider {
private static final Logger logger = LoggerFactory.getLogger(XMLTypeWriter.class);
public XMLTypeWriter(@Context Providers ps) {
super(ps, MediaType.APPLICATION_XML_TYPE);
}
@Override
protected boolean isSupported(MediaType m) {
return (m.equals(MediaType.APPLICATION_XML_TYPE) || m.equals(MediaType.TEXT_XML_TYPE));
}
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
// There is already a xmltype reader defined.
return false;
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type.isAnnotationPresent(XmlType.class) && isSupported(mediaType);
}
@Override
protected void writeTo(Object t, MediaType mediaType, Charset c, Marshaller m, OutputStream entityStream) throws JAXBException {
// need to get the type name from the annotation
XmlType xt = t.getClass().getAnnotation(XmlType.class);
JAXBElement p = null;
if (xt != null) {
String name = xt.name();
p = new JAXBElement(QName.valueOf(name), t.getClass(), t);
}
super.writeTo(p, mediaType, c, m, entityStream);
}
}