如何在Simple Framework中反序列化数组映射?

时间:2016-02-05 11:28:42

标签: java android xml 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>

进入这个班级

@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

怎么做?

2 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

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

很奇怪,但要创建数组地图,您需要使用特殊的SimpleFramework实用程序类@ElementList进行Dictionary修饰。插入该字典的对象必须实现Entry接口,并且可以包含任何解析规则。在我的情况下,它们包含与内部List<String>标记相对应的<return>

您可以在教程中阅读有关实用程序类的信息: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是一个实现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"