我正在使用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:元素'fruit'在类com.github.irshulx.fruitdiary.apps.main.model.EntryLog中的第-1行没有匹配项
这个错误没有意义。因为fruit
不属于EntryLog
。
非常感谢任何帮助。
这让它工作:
@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
,虽然我不确定如何修复异常。