预期为BEGIN_ARRAY,但在第1行第1列RetroFit中为STRING

时间:2019-07-17 03:33:10

标签: java android rx-java retrofit2

我有一个基本的lorem ipsum响应json url,如下所示: https://baconipsum.com/api/?type=all-meat&paras=10&start-with-lorem=10

在我的APIService接口中,我将其调用如下:

import io.reactivex.Observable;
import retrofit2.http.GET;

public interface APIService
{
    @GET("application/json")
    Observable<List<NewsFeed>> getProductData();
}

我使用响应数据的NewsFeed模型:

public class NewsFeed
{
    private String feed;

    public void setFeed(String feed)
    {
        this.feed = feed;
    }

    public String getFeed()
    {
        return feed;
    }

}

然后我正试图将这些数据从网址传递到我的recyclerview中...

        Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
    APIService apiService = retrofit.create(APIService.class);

    Observable<List<NewsFeed>> observable = apiService.getProductData().subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread());

    observable.subscribe(new Observer<List<NewsFeed>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<NewsFeed> newsFeeds)
        {
            newsFeedList = new ArrayList<>();
            for(int i = 0; i < newsFeeds.size(); i++)
            {
                NewsFeed newsFeedModel = new NewsFeed();
                newsFeedModel.setFeed(newsFeeds.get(i).getFeed());
                newsFeedList.add(newsFeedModel);
            }
            mAdapter = new NewsAdapter(getActivity(), newsFeedList);
            recyclerView.setAdapter(mAdapter);
            recyclerView.setHasFixedSize(true);
            recyclerView.setNestedScrollingEnabled(false);
        }

        @Override
        public void onError(Throwable e) {
            Log.e("Error", e.getMessage());
        }

        @Override
        public void onComplete() {

        }
    });
}

如何解决此错误?是否有处理字符串结果的特定方法?

1 个答案:

答案 0 :(得分:1)

您需要像这样的APIService接口

import io.reactivex.Observable;
import retrofit2.http.GET;

public interface APIService
{
    @GET("/api/?type=all-meat&paras=10&start-with-lorem=10")
    Observable<List<String>> getProductData();
}

然后在创建Retrofit实例的位置,将其编写为这样

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://baconipsum.com/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();

之后,无论您在使用NewsFeed类的任何地方,都将其替换为String