使用XML进行改造 - 元素在类

时间:2017-12-16 12:52:42

标签: java android xml retrofit2

我正在使用SimpleXmlConverterFactory和Retrofit2。以下是我试图解析的示例回复:

<entries timestamp="1513178530.8394">
 <entry id="2" date="20170104">
   <fruits>
      <fruit type="apple" count="16"/>
      <fruit type="banana" count="12"/>
      <fruit type="cerry" count="5"/>
      <fruit type="lemon" count="2"/>
      <fruit type="orange" count="2"/>
      <fruit type="pear" count="0"/>
      <fruit type="pineapple" count="2"/>
   </fruits>
 </entry>
<entry id="21" date="20170306">
   <fruits>
      <fruit type="pear" count="1"/>
      <fruit type="orange" count="3"/>
      <fruit type="banana" count="1"/>
      <fruit type="cerry" count="1"/>
      <fruit type="apple" count="2"/>
   </fruits>
 </entry>
</entries>

现在我使用以下类来解析:

@Root(name = "entries")
public class Entries {
    @Attribute(name = "timestamp")
    private String timestamp;
    @ElementList(name = "entry")
    private List<EntryLog> entry;
}

@Root(name = "entry")
class Entry {
    @Element(name = "fruits",required = false)
    private Fruits fruits;
}

@Root(name = "fruits")
class Fruits{
    @ElementList(name = "fruit")
    private List<FruitItem> fruit;
}

@Root(name = "fruit")
class Fruit {
    @Attribute(name = "type")
    private String type;
    @Attribute(name = "count")
    private int count;
}

我似乎无法让它发挥作用,错误说:

  

org.simpleframework.xml.core.ElementException:元素&#39;水果&#39;不   在课堂上没有比赛   第-1行的com.github.irshulx.fruitdiary.apps.main.model.EntryLog

这个错误没有意义。因为fruit不属于EntryLog

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

这让它发挥作用:

@Root(name = "entries")
public class Entries {

    @Attribute(name = "timestamp")
    private String timestamp;

    @ElementList(name = "entry",inline = true)
    private List<EntryLog> entry;
}


@Root(name = "entry")
class EntryLog {

    @Attribute(name = "id")
    private int id;

    @Attribute(name = "date")
    private String date;

    @Element(name = "fruits")
    private Fruits fruitItem;
}


@Root(name = "fruits")
class Fruits{

    @ElementList(name = "fruit",inline = true)
    private List<FruitItem> fruitItem;

}


@Root(name = "fruit")
class FruitItem {

    @Attribute(name = "type")
    private String type;

    @Attribute(name = "count")
    private int count;
}

必须添加inline = true,但我不确定如何修复该异常。