0

我有一个 JAX-RS 响应方法

@Produces('application/xml', 'application/json')

我还有一个 JAX-B 实体,它产生这个:

<person>
    <name>joe</name>
    <address>
        <street>123 home</street>
    </address>
<person>

对于这个电话/person/Joe

我想回应/person/joe/address

并返回

  <address>
       <street>123 home</street>
  </address>

使用 JAX-RS/Jersey 我得到一个错误:

当 mime 类型为 application/XML 时,没有 Address.class 类型的编组器

发生这种情况是因为地址对象未注释为@XMLRootElement.

4

2 回答 2

0

您可以Address使用.@XmlRootElementJAXBElement

new JAXBElement<Address>(
    new QName("address"), 
    Address.class, 
    address);
于 2013-02-22T09:52:17.303 回答
0

我编写了一个简单的提供程序来处理这种情况,它似乎按我的预期工作。它会将 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);
    }
}
于 2013-02-23T00:29:50.790 回答