简体   繁体   中英

Serializing a tree structure using JAXB in Java

So I have a tree implemented my custom tree structure moreless like this:

The tree class:

@XmlRootElement
public class Tree {

   Set<? extends TreeNode> nodes;
   @XmlElement
   Set<? extends TreeNode> getNodes() {...}
}

The abstract node:

public abstract class Node {
   Set<? extends Node> children;
   private String name;

   @XmlAttribute
   public String getName() {...}
   @XmlElement
   public abstract Set<? extends Node> getChildren();

}

The group (could contain groups and entities):

@XmlRootElement(name = "group")
public class Group extends Node {

    private final Set<Group> groups = new HashSet<Group>();
    private final Set<Entity> entities = new HashSet<Entity>();
    public Set<Group> getGeoups() { ... }
    public Set<Entity> getEntities() { ... }
} 

The node:

@XmlRootElement(name = "entity")
public class Entity extends Node {

    public Set<DashboardNode> getChildren() {
        return Collections.<DashboardNode> emptySet();
    }
}

My problem is, that JAXB doesn't use diffrent names for groups and entities. I would like to get result similar to:

<tree>
   <node>
       <group>
            <group>
                <entity/>
            </group>
       </group>
   </node>
   <node>
       <group>
           <entity/>
       </group>
       <group>
       </group>
       <entity/>
   </node>
</tree>

And I get this instead:

<tree>
   <node>
       <children>
            <children>
                <children/>
            </children>
       </children>
   </node>
   (...)
</tree>

IF i remove the annotation in my abstract node class on the getChildren() method I would reveive only this:

<tree>
   <node>
   </node>
  <node>
   </node>
</tree>

看一下@XmlElements批注,将其中合适的一项添加到Node的children属性中应该会达到您的期望。

The problem is that your group 'is-a' node. What is the serialiser to do when it encounters an object that both has 'children' and has 'groups'?

It may be better to avoid the java inheritance altogether.

Actually, you don't have a @XMLElement annotation on getGeoups() [sic] or getEntities() either...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM