How can I write objects on which I have no control in jaxb?

I am trying to find a way to marshall classes that i have no access to. I am trying to achieve something like this:

@XmlRootElement(name="bar")
class Bar {
  @XmlAttribute
  private Foo foo;

  @XmlAttribute
  private String baz;
}

which should result in a xml file like this:


Is this possible? I tried to fiddle with @XmlJavaTypeAdapter
with no sucess.

You’re on the right track with XmlJavaTypeAdapter, but I suspect foo needs to be an XmlElement rather than an XmlAttribute:

@XmlRootElement(name="bar")
public class Bar {

  @XmlElement
  @XmlJavaTypeAdapter(FooAdapter.class)
  private Foo foo;

  @XmlAttribute
  private String baz;

}

FooAdapter can be as simple as the following, but the output will be prettier if you make a proxy object to represent Foo and marshal that rather than Object[].

class FooAdapter extends XmlAdapter {

    @Override
    public Object[] marshal(Foo v) throws Exception {
        return new Object[]{ v.x, v.y, v.z };
    }

    @Override
    public Foo unmarshal(Object[] v) throws Exception {
        Foo foo = new Foo();
        foo.x = (String) v[0];
        foo.y = (Integer) v[1];
        foo.z = (Double) v[2];
        return foo;
    }

}
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » How can I write objects on which I have no control in jaxb?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录