给定以下类:
@XmlRootElement(name = "parent")
class Parent {
private Child child;
// What annotation goes here
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
class Child {
private Integer age;
@XmlElement(name = "age")
public Integer getAge() {
return age;
}
public void setAge(Integer Age) {
this.age = age;
}
}
我需要添加什么注解(注解所在的地方)才能得到下面的xml:
<parent>
<age>55</age>
</parent>
我只是想出了具体的例子,所以让标 checkout 现在它所在的位置可能没有意义。但我真正想知道的是如何传递到 Child 类。基本上很容易为以下内容进行映射(我不想要):
<parent>
<child>
<age>55</age>
</child>
</parent>
最佳答案
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
@XmlRootElement
class Parent {
public static void main(String[] args) throws JAXBException {
final Child child = new Child();
child.age = 55;
final Parent parent = new Parent();
parent.child = child;
final JAXBContext context = JAXBContext.newInstance(Parent.class);
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
marshaller.marshal(parent, System.out);
System.out.flush();
}
@XmlElement
public Integer getAge() {
return child == null ? null : child.age;
}
@XmlTransient
private Child child;
}
class Child {
@XmlElement
protected Integer age;
}
打印
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
<age>55</age>
</parent>
关于java - JAXB 通过映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10904804/