如何在简单框架中反序列化数组映射?

How to deserialize a Map of Arrays in Simple Framework?

我正在尝试 deserialize 关注 xml:

<scenario name="test responses">
    <cmd name="query1">
        <return>success_200.xml</return>
        <return>error_500.xml</return>
    </cmd>
    <cmd name="query2">
        <return>success_200.xml</return>
    </cmd>
</scenario>

进入这个class

@Root(name="scenario")
public class TestScenario {
    @ElementMap(entry="cmd", key="name", attribute=true, inline=true)
    private Map<String,StepsList> scenario;

    @Attribute(required = false)
    private String name = "";

    public static class StepsList {
        @ElementList(name="return")
        private List<String> steps = new ArrayList<String>();

        public List<String> getSteps() {
            return steps;
        }
    }
}

但是得到一个org.simpleframework.xml.core.ValueRequiredException:无法满足@org.simpleframework.xml.ElementList

如何实现?

试试这个:

@ElementList(required = false, inline = true, name="return")
private List<String> steps = new ArrayList<String>();

因此,经过几个小时的研究,我创建了一个可行的解决方案。

很奇怪,但是要创建数组映射,您需要使用具有特殊 SimpleFramework 实用程序的 @ElementList 修饰 class Dictionary。插入该字典的对象必须实现 Entry 接口并且可以包含任何解析规则。在我的例子中,它们包含 List<String> 对应于内部 <return> 标签。

您可以在教程中阅读实用程序 classes:http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#util

@Root(name="scenario")
public class TestScenario {
    @ElementList(inline=true)
    private Dictionary<StepsList> scenario;

    @Attribute(required = false)
    private String name = "";

    public Dictionary<StepsList> getScenario() {
        return scenario;
    }

    @Root(name="cmd")
    public static class StepsList implements Entry {
        @Attribute
        private String name;

        @ElementList(inline=true, entry="return")
        private List<String> steps;

        @Override
        public String getName() {
            return name;
        }

        public List<String> getSteps() {
            return steps;
        }
    }
}

Dictionary 是 class 实现 java.util.Set,你可以这样使用它:

TestScenario test = loadScenario("test.xml");
String step1 = test.getScenario().get("query1").getSteps().get(0);
// step1 is now "success_200.xml"
String step2 = test.getScenario().get("query1").getSteps().get(1);
// step2 is now "error_500.xml"