【问题标题】:Jax-rs client marshal list of entities using jax-b使用 jax-b 的 Jax-rs 客户端编组实体列表
【发布时间】:2012-10-23 09:08:27
【问题描述】:

我需要在 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

编辑:

这是来自客户类的一个 sn-p:

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

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

【问题讨论】:

  • 请提供更多用于编组对象列表的代码。
  • 希望这会有所帮助,如果没有,请不要犹豫,要求更多;)

标签: jaxb jax-rs


【解决方案1】:

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

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多