Retrofit和SimpleXmlConverterFactory

时间:2017-09-15 09:36:48

标签: java android xml retrofit simple-xml-converter

我有改造和XML的问题,我使用SimpleXmlConverterFactory,我有这个错误:引起:“java.lang.IllegalArgumentException:无法找到java.util.List的ResponseBody转换器。 尝试:
* retrofit2.BuiltInConverters * retrofit2.converter.simplexml.SimpleXmlConverterFactory“

的gradle:

compile 'com.google.code.gson:gson:2.8.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
compile ('com.squareup.retrofit2:converter-simplexml:2.3.0') {
    exclude group: 'xpp3', module: 'xpp3'
    exclude group: 'stax', module: 'stax-api'
    exclude group: 'stax', module: 'stax'
}

服务:

        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(buildHttpClient())
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .build();

private OkHttpClient buildHttpClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return (new OkHttpClient.Builder())
            .addInterceptor(buildDefaultHeadersInterceptor())
            .addNetworkInterceptor(buildLogInterceptor())
            .build();
}

模特:

    @Root(name = "item")
    public class Item {

    @Element(name = "link")
    private String link;

    @Element(name = "title")
    private String title;

    @Element(name = "description")
    private String description;

    public Item() {}
}

xml:

<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
   <channel xml:lang="fr">
       <title>...</title>
       <link>http://www.jouars-pontchartrain.fr/</link>
       <description>...</description>
       <language>fr</language>
       <generator>SPIP - www.spip.net</generator>
       <image>...</image>
       <item xml:lang="fr">
           <title>
              title here
           </title>
           <link>
              link here
           </link>
           <description>
              description here
           </description>
       </item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
   </channel>
</rss>

1 个答案:

答案 0 :(得分:0)

遇到同样的问题。解决方案是使内部类静态化(或仅创建一个新的单独的Java类)。还要为“通道”节点添加“根”注释。

    @Root(name = "rss", strict = false)
public class ArticleResponse {

@Element(name = "channel")
private Channel channel;


@Root(name = "channel", strict = false)
static class Channel {

    @ElementList(inline = true, name="item")
    private List<Article> articles;
  }

}

与“附件”和“源”节点相同-创建新文件或创建静态内部类。

public class Enclosure {

    @Attribute(name = "url")
    private String url;

    @Attribute(name = "length")
    private long length;

    @Attribute(name = "type")
    private String type;
}