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

综合编程 2017-12-31

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!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

Migrating From JAXB XML Processing to XStream I have a small REST API application that uses Spark and GSON and JAXB. I haven’t released this to GitHub yet, but I did release some of the example's...
Migrating From JAXB XML Processing to XStream I have a small REST API application that uses Spark and GSON and JAXB. I haven’t released this to GitHub yet, but I did release some of the example's...
The jaxb2 maven plugin does not work on the second... I have a modular project in which, for every single module, I use jaxb2-maven-plugin to compile XSD files with xjc. Now, suppose the modules are compi...
使用JAXB类库实现JAVA对象与XML互转 零、前言 XML是开发中常用的配置文件类型,在常用的组件包里也能时常看到它的踪影,如Spring中的applicationContext.xml、Hibernate中的hbm.xml,都是用的XML来配置相关的参数信息。可见其使用是十分广泛的。 但是在Java中,要解析一个XML,...
The Jaxb binding file is ignored I having a bit of trouble building JAXB bindings fora set of schemas and its driving me a bit batty. Here is the schema in question (it is just one of...