使用 XML 进行改造 - 元素在类中没有匹配项

Irs*_*shu 6 java xml android retrofit2

我正在使用SimpleXmlConverterFactoryRetrofit2。以下是我试图解析的示例响应:

<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>
Run Code Online (Sandbox Code Playgroud)

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

@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;
}
Run Code Online (Sandbox Code Playgroud)

我似乎无法让它工作,错误说:

org.simpleframework.xml.core.ElementException:元素“fruit”在第 -1 行的 com.github.irshulx.fruitdiary.apps.main.model.EntryLog 类中没有匹配项

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

非常感谢任何帮助。

Irs*_*shu 8

这让它工作:

@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;
}
Run Code Online (Sandbox Code Playgroud)

不得不添加inline = true,虽然我不确定如何修复异常。

  • 您可以在此处阅读有关内联的更多信息 http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#inline (2认同)