【问题标题】:Retrofit simpleXML Converter for nested arrays为嵌套数组改造 simpleXML 转换器
【发布时间】:2015-12-29 18:43:04
【问题描述】:

我无法弄清楚如何为 simplexml 创建 POJO 模型。

假设我有一个要从中提取数据的 xml,如下所示:

<root>
    <station>
        <station>
            <abbr>Abbr1</abbr>
        </station>
    </station>
    <station>
        <station>
            <abbr>Abbr2</abbr>
        </station>
    </station>
    <station>
        <station>
            <abbr>Abbr3</abbr>
        </station>
    </station>
</root>

所以基本上我认为我在一个数组中有一个数组,所以我像这样编写了我的 java 模型:

@org.simpleframework.xml.Root(name="root")
public class Root {
    @Element(name="stations")
    public Stations stations;

    @Element(name="station")
    public Station[] station;

    @Element(name="abbr")
    public String abbr;
    public class Stations{
        public Station[] station;
    }

    public class Station{
        public String abbr;
    }
}

我尝试调整注释,但无法正常工作。非常感谢您的帮助,谢谢。

【问题讨论】:

  • 您的第三行显示@Element(name="stations"),但您的XML 中没有stations [复数] 元素。他们都说只是station [单数]。

标签: android xml retrofit simple-framework


【解决方案1】:

我发现 XML 结构有点奇怪,因为子站标记似乎是多余的。不过,如果这是您想要的,那么这些是可以为您工作的带注释的 POJO(我将您的 'Root' 类替换为 'MyResponse'):

@Root
public class Station {
    @Path("station")
    @Element(name = "abbr") String abbr;
}

@Root
public class MyResponse {
    @ElementList(entry = "station", inline = true)
    ArrayList<Station> stationsList;
}

也就是说,我使用@ElementList 来注释父“站”标签列表而不是普通的@Element 注释:对于这些情况,简单的xml 框架同时具有@ElementList@ElementArray,我更喜欢前者。

此外,由于子“站”标签似乎没有实际用途,我使用 @Path 注释“跳过”了它们。

如果您想了解更多关于这些技术的信息,请try looking into the Simple XML documentation on lists

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-15
    • 2021-04-06
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多