当字段声明为List但当相同字段声明为ArrayList时,JAXB解组不起作用

时间:2014-07-03 07:28:20

标签: jaxb unmarshalling

我最近开始研究包含一些JAXB可序列化/可反序列化类的代码。其中一个类中有一些列表,我想为它添加一个新列表。这些列表最初被声明为ArrayList。同样,get方法也返回了ArrayList。我将所有这些更改为List并添加了新列表以及List。但在那之后,我无法将此对象的xml解组为JAVA对象。当我将字段更改回ArrayList而没有任何其他更改时,解组工作正常。我还尝试将DefaultValidationEventHandler附加到Unmarshaller,但在解组时它不会吐出任何错误。下面是类和变量名称的类似变化

@XmlRootElement(name = "commandSet")
public class CommandSet {

    private final ArrayList<Command> xCommands;

    private final ArrayList<Command> yCommands;

    @Override
    @XmlElementWrapper(name = "xCommands")
    @XmlElement(name = "xCommand", type = Command.class)
    public ArrayList<Command> getXCommands() {
        return this.xCommands;
    }

    @Override
    @XmlElementWrapper(name = "yCommands")
    @XmlElement(name = "yCommand", type = Command.class)
    public ArrayList<Command> getYCommands() {
        return this.yCommands;
    }
}

当xCommands和yCommands声明为List并且getter也返回List时,unmarhsalling不起作用。

在我找到的用于解组列表的所有示例中,人们使用了List&lt;&gt;而不是ArrayList&lt;&gt;。任何想法为什么它不适用于List&lt;&gt;?

1 个答案:

答案 0 :(得分:0)

我注意到您的代码的事情

我注意到您的代码有一些奇怪的事情可能会或可能不会影响您的问题。至少我怀疑你遇到问题的模型与你在问题中发布的模型不同。

  • 您将字段标记为final,但从不初始化它们。
  • 您使用get注释了两个@Override方法,但由于CommandSet不会从任何内容(Object除外)继承,因此您不是CommandSet。覆盖任何事情。

完整的工作示例

Java模型

<强>命令集

ArrayList类的这个版本中,我创建了一个属性类型List,另一个类型为import java.util.*; import javax.xml.bind.annotation.*; @XmlRootElement public class CommandSet { private final ArrayList<Command> xCommands; private final List<Command> yCommands; public CommandSet() { xCommands = new ArrayList<Command>(); yCommands = new ArrayList<Command>(); } @XmlElementWrapper(name = "xCommands") @XmlElement(name = "xCommand") public ArrayList<Command> getXCommands() { return this.xCommands; } @XmlElementWrapper(name = "yCommands") @XmlElement(name = "yCommand") public List<Command> getYCommands() { return this.yCommands; } } ,以证明它们都有效。我还删除了上面提到的代码的奇怪之处。

public class Command {
}

<强>命令

import java.io.File;
import javax.xml.bind.*;

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("input.xml");
        CommandSet commandSet = (CommandSet) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(commandSet, System.out);
    }

}

演示代码

<强>演示

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<commandSet>
    <xCommands>
        <xCommand/>
        <xCommand/>
    </xCommands>
    <yCommands>
        <yCommand/>
        <yCommand/>
    </yCommands>
</commandSet>

<强> input.xml中/输出

{{1}}
相关问题