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

标签 java android xml retrofit2

我在 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/

相关文章:

java - hibernate : Strange TypeCast Exception Thrown While retrieving records in Java from postgres database table

android - 按钮上的动画 View 单击android

python - Reg 将数据添加到 Python 中的现有 XML

java - 为什么要同步Java方法Provider.getService(String type,String algorithm)?

java - Android: Activity 建立网络连接

android - 缺少主调度程序的模块

Android:调整自定义 View 的大小。父级已调整大小但宽度/高度更改未传递给 subview

java - 找不到元素 'mvc:annotation-driven' 的声明

android - @android :id/* and @+id/* 之间的区别

java - 在 Java 中,当值为 null 时,收集器映射抛出 NullPointerException,为什么?