我正在尝试为Android编写一个简单的RSS阅读器应用程序。我使用Retrofit与SimpleXMLConverter进行网络通信,从XML填充POJO。这是我的REST API:
package ru.unatco.rss.data;
import java.util.List;
import retrofit.Callback;
import retrofit.http.GET;
public interface RssAdapter {
@GET("/radio-t")
void getItems(Callback<RadioTItems> callback);
}
这是调用API的代码:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://feeds.rucast.net")
.setConverter(new SimpleXMLConverter())
.build();
RssAdapter rssAdapter = restAdapter.create(RssAdapter.class);
rssAdapter.getItems(new Callback<RadioTItems>() {
@Override
public void success(RadioTItems radioTItems, Response response) {
System.out.println(radioTItems.toString());
}
@Override
public void failure(RetrofitError error) {
System.out.println(error);
}
});
这些是我想要获得的POJO:
package ru.unatco.rss.data;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import java.util.List;
@Root(name = "rss", strict = false)
public class RadioTItems {
@ElementList(required = false, name = "channel")
List<RadioTItem> items;
}
package ru.unatco.rss.data;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root(name = "item", strict = false)
public class RadioTItem {
@Element(name = "title")
String mTitle;
@Element(name = "description")
String mDescription;
public RadioTItem() {}
}
RSS的来源是here。 现在,当我尝试执行请求时,我得到了这个例外:
retrofit.RetrofitError: org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy @org.simpleframework.xml.Element(data=false, name=description, required=true, type=void) on field 'mDescription' java.lang.String ru.unatco.rss.data.RadioTItem.mDescription for class ru.unatco.rss.data.RadioTItem at line 2
如果我在RadioTItem mDescription
中设置mTitle
和@Element(required = false)
字段,则解析完成,但两个字段均为空。
任何想法如何摆脱这个问题?
答案 0 :(得分:2)
好的,经过多次尝试 - 失败循环后,我找到了一个可行的解决方案。我完全重写了我的POJO,这就是我所拥有的:
package ru.unatco.rss.data;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root(name = "rss", strict = false)
public class Feed {
@Element(name = "channel")
private Channel mChannel;
public Channel getmChannel() {
return mChannel;
}
}
package ru.unatco.rss.data;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import ru.unatco.rss.model.Item;
@Root(name = "channel", strict = false)
public class Channel {
@ElementList(inline = true)
private List<FeedItem> mFeedItems;
public List<FeedItem> getFeedItems() {
return mFeedItems;
}
}
package ru.unatco.rss.data;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import ru.unatco.rss.model.Item;
@Root(name = "item", strict = false)
public class FeedItem {
@Element(name = "title")
private String mTitle;
@Element(name = "description")
private String mDescription;
public String getTitle() {
return mTitle;
}
public String getDescription() {
return mDescription;
}
}
通过所有这些改变,我能够得到我想要的东西。