考虑到MOXy,我仍然坚持(我猜)一个非常微不足道的问题。将类似于此示例(pastebin)的类转换为XML是没有问题的,将其转换回来也没有任何错误。但是,引用另一个(或更多)Person
的字段将导致空值。
有没有办法在不失去关系的情况下完成这项工作?我的猜测是这只是由ID引用,因为JAXB无法知道其他现有对象。我尝试过使用@XmlInverseReference
,但每次尝试都会导致无限循环。
答案 0 :(得分:2)
EclipseLink MOXy的@XmlInverseReference
用于解决无限循环问题。我将在下面演示一个基于您的模型的示例:
<强>人强>
package forum15821738;
import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Person implements Serializable {
private String name;
@XmlInverseReference(mappedBy="children")
private Person parent;
@XmlElementWrapper
@XmlElement(name="child")
private List<Person> children;
public Person getParent() {
return parent;
}
public List<Person> getChildren() {
return children;
}
// OTHER GETTERS AND SETTERS
}
<强> jaxb.properties 强>
要将MOXy指定为JAXB提供程序,您需要在与域模型相同的包中包含名为jaxb.properties
的文件,并带有以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
<强>演示强>
package forum15821738;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum15821738/input.xml");
Person person = (Person) unmarshaller.unmarshal(xml);
for(Person child : person.getChildren()) {
System.out.println(child.getParent());
}
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(person, System.out);
}
}
<强>输入/输出强>
forum15821738.Person@5893a012
forum15821738.Person@5893a012
<?xml version="1.0" encoding="UTF-8"?>
<person>
<name>Jane</name>
<children>
<child>
<name>Bobbie</name>
</child>
<child>
<name>Sue</name>
</child>
</children>
</person>
了解更多信息