简体   繁体   English

在Java中使用JAXB序列化树结构

[英]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. 我的问题是,JAXB不为组和实体使用不同的名称。 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: 如果我在getChildren()方法上的抽象节点类中删除了注释,则仅会显示以下内容:

<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. 最好完全避免继承Java。

Actually, you don't have a @XMLElement annotation on getGeoups() [sic] or getEntities() either... 实际上,您在getGeoups() [sic]或getEntities()上都没有@XMLElement批注...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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