我在尝试使用Retrofit来解析我的JSON时遇到了很多麻烦,我无法解决这个问题。每当我运行我的Retrofit代码时,我都会崩溃:
Caused by: java.lang.StackOverflowError: stack size 1036KB
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:537)
然后是:
E/JavaBinder﹕ !!! FAILED BINDER TRANSACTION !!!
我的JSON看起来像这样:
{
"199" : {
"anncontent" : "content",
"anndisplaydate" : "Tuesday February 11",
"announcements_id" : "199",
"anntitle" : "Newsletter Issue 17"
},
"264" : {
"anncontent" : "content",
"anndate" : "2014-10-03 22:37:32",
"anndisplaydate" : "Friday October 03",
"announcements_id" : "264",
"anntitle" : "Timetable"
},
"267" : {
"anncontent" : "content",
"anndate" : "2014-10-10 02:41:32",
"anndisplaydate" : "Friday October 10",
"announcements_id" : "267",
"anntitle" : "Author talk with Hugh O’Brien"
}
}
我的公告类字段如下所示:
private String anntitle;
private String anncontent;
private String anndisplaydate;
private Date anndate;
private String announcements_id;
我的界面如下所示:
public interface AnnouncementsAPI {
@GET("/announcements.json")
ArrayList<Announcement> listAnnouncements();}
最后,我的Retrofit代码如下所示:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://MYURL")
.build();
AnnouncementsAPI announcementsAPI = restAdapter.create(AnnouncementsAPI.class);
ArrayList<Announcement> announcements = announcementsAPI.listAnnouncements();
Log.d("RETROFIT", "Announcemnts: " + announcements.toString());
我只是想获取一个AnnounceList对象的ArrayList,我不知道该怎么做。很抱歉,如果之前已经询问过,但我发现的所有先前的问题/示例都使用了与我的看似截然不同的JSON。
如果有人有任何想法,我会非常感激。 感谢
答案 0 :(得分:2)
如果所有对象都扩展了相同的基础对象,那么StackOverflowError:堆栈大小为1036KB异常。
例如:
class BaseBean
class A extends BaseBean
(class A
包含class A
和class B
)的引用
class B extends BaseBean
class C extends BaseBean
实施上述情况,发生相同异常的可能性很大。 (不要使用BaseBean进行扩展)。
答案 1 :(得分:1)
尝试使用retrofit callback
作为您的界面,如下所示:
界面
public interface AnnouncementsAPI {
@GET("/announcements.json")
void listAnnouncements(Callback<ListAnnouncement> callback);
}
如果您希望返回为List,请将公告类封装到另一个类中,如下所示:
<强> ListAnnouncement.Java 强>
public class ListAnnouncement {
private List<Announcement> fieldname; //match the fieldname with the field name on the JSON
//add getter-setter as needed
}
改造代码
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://MYURL")
.build();
AnnouncementsAPI announcementsAPI = restAdapter.create(AnnouncementsAPI.class);
final ListAnnouncement listAnnouncement;
announcementsAPI.listAnnouncements(new Callback<ListAnnouncement>() {
@Override
public void success(ListAnnouncement data, Response response) {
listAnnouncement = data;
}
@Override
public void failure(RetrofitError error) {
}
}
);
之后,您可以使用fieldname
ListAnnouncement
上的Class
获取Announcement
的列表。
重要强>
如果您的JSON确实是JSON Array
,上面的代码将起作用,通过它的外观,您将获得具有不同键的几个Announcement
对象的返回,这不是{{1} }
答案 2 :(得分:-1)
试试这个。响应应采用此格式HashMap<String,Announcement>