繁体   English   中英

JAXB继承+ XMLAdapter(HasMap)

[英]JAXB Inheritance + XMLAdapter (HasMap)

我正在制作一个应用程序,它将包含XML文件中的数据。

我现在遇到一个问题:JAXB不会编组我的子类,因此当我umarshall XML文件时,所有对象都是Parent类的对象。 我尝试了@XMLSeeAlsoAccessType.FIELDJAXBContext jaxbContext = JAXBContext.newInstance(Important.class, Parent.class, Child.class);一些变体JAXBContext jaxbContext = JAXBContext.newInstance(Important.class, Parent.class, Child.class); ,但似乎我误会了一些东西,并且不起作用。

你能给我一些建议吗? 我应该使用什么注释? 或MB XMLAdapter? 我项目的当前结构是(我试图简化它):

Main.java

public class Main {
    public static void main(String args[]){
        JAXB jaxb = new JAXB();
        Parent parent = new Parent(1);
        Child child = new Child(2,3)
        Important important = new Important();
        jaxb.write(important);
    }
 }

Important.java

@XmlRootElement(name="important")
public class Important {
public Map<Integer, Parent> hashMap;
    //some code here
}

Parent.java

public class Parent{
    public int parentField;
    //constructor
}

Child.java

public class Child extends Parent {
    public int childField;
    //constructors
}

和简单的JAXB类。 JAXB.java

public class JAXB {
    public void write(Important important) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Important.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(important, System.out);

        } catch (JAXBException e) {
            System.err.println(e + "Error.");
        }
    }
}

但是,在将其编组后返回XML,其中不包含有关child的任何信息。

<important>
   <hashMap>
       <entry>
           <key>0</key>
           <value>
               <parentField>1</parentField>
           </value>
       </entry>
       <entry>
           <key>0</key>
           <value>
               <parentField>2</parentField>
           </value>
       </entry>
   </hashMap>

然后关闭标签。

我的地图100%包含不同类型的类别:父级和子级

有什么想法吗?

@XmlSeeAlso批注使JAXBContext知道您的子类。

@XmlSeeAlso(Child.class)添加到您的Parent类应该可以解决问题。

作为参考,另请参见使用JAXB将子类实例作为超类传递的公认答案。

拟议的解决方案

@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso(Child.class)
public class Parent {

    public int parentField;

    public Parent(Integer parentField) {
        this.parentField = parentField;
    }
}

结果对我来说

<important>
    <map>
        <entry>
            <key>0</key>
            <value>
                <parentField>1</parentField>
            </value>
        </entry>
        <entry>
            <key>1</key>
            <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="child">
                <parentField>2</parentField>
                <childField>3</childField>
            </value>
        </entry>
    </map>
</important>

暂无
暂无

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

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