0

我需要在 jax-rs 客户端中使用 jax-b 编组一个实体列表,而不需要为每个需要的实体创建一个包装类(有很多实体!)。我注意到该服务能够编组这样的客户列表:

<customers>
    <customer>.....</customer>
    <customer>.....</customer>
</customers>

我在客户端能够通过查找所有客户节点并将它们手动添加到列表中来解组。(我想有更好的方法来做到这一点?)

现在,真正的问题是当我想向服务发送实体(例如客户)列表时。在将此字符串作为对服务的请求的有效负载之前,我想将此列表编组为一个 xml 字符串。这不起作用,因为编组器不知道 java.util.List 或其后代。

javax.xml.bind.Marshaller.marshal(list, StringWriter);
javax.xml.bind.Unmarshaller.unmarshal(org.​w3c.​dom.node)

任何帮助深表感谢!

谢谢!-Runar

编辑:

这是客户类的一个片段:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer implements Serializable {
    private String name;
    .....
}

我正在尝试使用不属于标准实现的第 3 方库来编写轻量级客户端。因此,我编写了自己的 httpclient 接收有效负载对象,将它们编组并将它们传递给请求的有效负载。收到响应后,我读取 xml 并将其发送到解组。如果我可以像我的 jax-rs 服务那样直接对字符串进行编组/解组,那就太棒了。

4

1 回答 1

0

好的,所以我没有找到很好的解决方案。但由于我的 jax-rs 服务的模式似乎是生成一个名为 的根节点<class name " + "s>,所以我这样做是为了能够将对象列表发送到服务:

if (obj instanceof List) {
    List list = (List) obj;
    if (!list.isEmpty()) {
        // Since the jax-b marshaller does not allow to send lists directly,
        // we must attempt to create the xml as the jax-rs service would expect them,
        // wrapped with the classname pluss an s.
        String wrapper = list.get(0).getClass().getSimpleName() + "s";
        // Make first letter in class-name lower-case
        wrapper = Character.toLowerCase(wrapper.charAt(0)) +
                  (wrapper.length() > 1 ? wrapper.substring(1) : "");
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FRAGMENT, true);
        writer.write("<" + wrapper + ">");
        for (Object o : (List) obj) {
            marshaller.marshal(o, writer);
        }
        writer.write("</" + wrapper + ">");
    }
} else {
    marshaller.marshal(obj, writer);
}
于 2012-10-23T10:13:11.613 回答