Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit with XML - Element does not have a match in class

I'm using SimpleXmlConverterFactory with Retrofit2. Below is the sample response i'm trying to parse:

<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>

Now i'm using the following class to parse:

@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;
}

I can't seem to get it work, the error says:

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

This error doesn't make sense. Because fruit does not belong in EntryLog.

Any helps is much appreciated.

like image 557
Irshu Avatar asked Dec 16 '17 12:12

Irshu


1 Answers

This got it working:

@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;
}

had to add inline = true , although i'm not sure how that fixes the exception.

like image 70
Irshu Avatar answered Sep 30 '22 18:09

Irshu