好吧,我正在使用REST API响应来解决Firebase响应问题。问题是我不想使用Android的用于Firebase的库,而是使用原始的rest api。长话短说,Firebase的回应是:
{
"object1": {
"param1": true,
"param2": "05",
"param3": "String",
},
"object2": {
"param1": true,
"param2": "09",
"param3": "String",
}
}
改造界面:
public interface ApiCalls {
@GET("/objects.json")
Observable<List<MyObject>> getObjects();
}
Gson Builder,Retrofit Builder和RxJava:
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://my-service.firebaseio.com")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.build();
ApiCalls api = retrofit.create(ApiCalls.class);
rx.Observable<List<MyObject>> call2 = api.getObjects();
call2.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<MyObject>>() {
@Override
public void onCompleted() {
Log.d("onCompleted", "Its completed");
}
@Override
public void onError(Throwable e) {
Log.d("onError", e.getMessage());
}
@Override
public void onNext(List<MyObject> MyObjects) {
Log.d("onNext", "NextItem");
}
});
执行此操作时,我收到错误:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
无论如何使用RxJava来解决这个问题,以便迭代来自服务器的对象列表?从现在开始我期待一个数组,但firebase的响应不是一个数组,无论如何要解决这个问题吗?
答案 0 :(得分:3)
好吧,多亏了这个评论,我可以解决这个问题:
@VeereshCharantimath确实是错误的原因:来自Firebase的JSON是地图(Map),而不是列表。小心发布答案? - 弗兰克范普弗伦
在我修改了响应的预期值后,它开始工作:
改造Api电话
public interface ApiCalls {
@GET("/objects.json")
Observable<HashMap<String, MyObject>> getObjects();
}
RxJava
rx.Observable<HashMap<String, MyObject>> call2 = api.getObjects();
call2.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<HashMap<String, MyObject>>() {
@Override
public void onCompleted() {
Log.d("onCompleted", "Its completed");
}
@Override
public void onError(Throwable e) {
Log.d("onError", e.getMessage());
}
@Override
public void onNext(HashMap<String, MyObject> MyObjects) {
Log.d("onNext", "NextItem");
}
});