我在 Retrofit2 中使用 SimpleXmlConverterFactory
。以下是我尝试解析的示例响应:
<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: Element 'fruit' does not have a match in class com.github.irshulx.fruitdiary.apps.main.model.EntryLog at line -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
,尽管我不确定如何修复异常。
关于java - 使用 XML 进行改造 - 元素在类中没有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845878/