[英]How to fetch JSONArray using retrofit2 and RXJava2
I am using Retrofit2 and RxJava2 for fetching data from the server.I have response in below format:我正在使用 Retrofit2 和 RxJava2 从服务器获取数据。我有以下格式的响应:
{
"product_data": [
{
"product_name": "Pi-Pi jod kar ye Notebook li hai",
"product_price": "249.00",
"category_id": "9",
"product_id": "125",
"product_photo": "1574935198_1.jpg"
},
{
"product_name": "Tere Jesa year kaha kaha esa yarana",
"product_price": "249.00",
"category_id": "9",
"product_id": "128",
"product_photo": "1574935455_1.jpg"
}
]
}
I am getting exception below:我在下面收到异常:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $.
ApiService.class ApiService.class
public interface ApiService {
@GET("general_cat_api")
Observable<List<HomeGeneralModel>> getData();
}
RetrofitClient.class RetrofitClient.class
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getInstance(){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(22, TimeUnit.SECONDS)
.readTimeout(22, TimeUnit.SECONDS)
.writeTimeout(22, TimeUnit.SECONDS)
.build();
if(retrofit == null)
retrofit = new Retrofit.Builder()
.baseUrl("http://aamku.com/api/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
private RetrofitClient(){
}
}
Now I am using retrofit some thing like below to fetch data:现在我正在使用像下面这样的改造来获取数据:
private void getData(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService myApi = retrofit.create(ApiService.class);
myApi.getData().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<MenuModel>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(List<MenuModel> menuModels) {
if(menuModels.size() > 0){
menuProg.setVisibility(View.INVISIBLE);
list.addAll(menuModels);
adapter = new MenuAdapter(list,MainActivity.this);
menuRecycler.setAdapter(adapter);
}
}
@Override
public void onError(Throwable e) {
menuProg.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
@Override
public void onComplete() {
}
});
}
Someone please let me know why I am getting this exception.Any help would be appreciated.有人请让我知道为什么我会收到此异常。任何帮助将不胜感激。
THANKS谢谢
Your response format is wrong here您的回复格式在这里是错误的
Observable<List<HomeGeneralModel>> getData();
Since you are getting a json object in response, you don't need the List.由于您正在获得一个 json 对象作为响应,因此您不需要 List。 Use HomeGeneralModel
directly in observable.在 observable 中直接使用HomeGeneralModel
。
Your list of product_data
should be inside of HomeGeneral Model您的product_data
列表应该在 HomeGeneral 模型内
It should be like this应该是这样的
Observable<HomeGeneralModel> getData();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.