Can XStream be configured to use bidirectional (parent / child) links?

I use XStream to upload a file structured as follows:

<parent>
  <child/>
  <child/>
</parent>

In a class like this:

public class Parent(){
 private List<Child> children;
}

public class Child { 
 private Parent parent; 
}

I would like to be able to do this: parent.getChildren().get(0).getParent()

I would like to be able to use XML when it sits. I know that I can add references to the parent under the children, but this seems very redundant. I know the childs parent because of its XML structure.

Does XStream support this?

+3
source share
3 answers

Xstream , . , , , , . , , "", .

.

+3

- readResolve . , XStream: http://x-stream.imtqy.com/faq.html#Serialization_initialize_transient

readResolve, Parent , .

public class Parent {
  private List<Child> children = new ArrayList<Child>();
  private Object readResolve() {
    for( Child child: children ) {
      child.setParent(this);
    }
    return this;
  }
}
+2

- , XStream, EclipseLink JAXB (MOXy) @XmlInverseReference ( - MOXy).

:

import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Parent {

    private List<Child> children;

    @XmlElement(name="child")
    public List<Child> getChildren() {
        return children;
    }

    public void setChildren(List<Child> children) {
        this.children = children;
    }

}

( @XmlInverseReference ):

import org.eclipse.persistence.oxm.annotations.XmlInverseReference;

public class Child {

    private Parent parent;

    @XmlInverseReference(mappedBy="children")
    public Parent getParent() {
        return parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }

}

- : (input.xml XML ):

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Parent.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Parent parent = (Parent) unmarshaller.unmarshal(new File("input.xml"));

        for(Child child : parent.getChildren()) {
            System.out.println(child.getParent());
        }
    }

}

MOXy JAXB, jaxb.properties , , :

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

JAXB XStream:

0
source

Source: https://habr.com/ru/post/1785518/


All Articles