JAXB解组列表以映射适配器

问题描述

<?xml version='1.0' encoding='UTF-8' standalone='no' ?>
<Result>
    <Module name="module">
        <TestCase name="testCase1"></TestCase>
        <TestCase name="testCase2"></TestCase>
        <TestCase name="testCase3"></TestCase>
    </Module>
</Result>

我想将TestCase的列表转换为 HashMap

Result.java

@XmlRootElement(name = "Result")
public class Result {

    @XmlElement(name = "Module")
    private List<Module> modules;
}

Module.java

public class Module {

    @XmlAttribute
    public String name;

    @XmlJavaTypeAdapter(TestCaseAdapter.class)
    @XmlElement(name = "TestCase")
    private Map<String,TestCase> testCases;

}

TestCase.java

public class TestCase {

    @XmlAttribute
    private String name;
}

TestCaseAdapter.java

public class TestCaseAdapter extends XmlAdapter<List<TestCase>,Map<String,TestCase>> {

    @Override
    public Map<String,TestCase> unmarshal(List<TestCase> testCases) throws Exception {
        Map<String,TestCase> map = new HashMap<>();
        for (TestCase testCase : testCases) {
            map.put(testCase.getName(),testCase);
        }
        return map;
    }

    @Override
    public List<TestCase> marshal(Map<String,TestCase> testCaseMap) throws Exception {
        return new ArrayList<>(testCaseMap.values());
    }
}

但是,以上代码无法正常运行。执行代码时,会出现以下错误

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions

java.util.List is an interface,and JAXB can't handle interfaces.
    this problem is related to the following location:
        at java.util.List
        at private java.util.Map com.nebula.parser.model.Module.testCases
        at com.nebula.parser.model.Module
        at private java.util.List com.nebula.parser.model.Result.modules
        at com.nebula.parser.model.Result

因此,我更改了以下代码,并且效果很好。但 TestCase []为空

public class TestCaseAdapter extends XmlAdapter<TestCase[],TestCase> unmarshal(TestCase[] testCases) throws Exception {
        return null;
    }

    @Override
    public TestCase[] marshal(Map<String,TestCase> testCaseMap) throws Exception {
        return new TestCase[0];
    }
}

我想解决这个问题,但我无法解决。如果您能帮助我,我会很感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)