Retrofit和Rxjava&#34;无法为java.util.List创建转换器<model>&#34;

时间:2018-05-09 11:55:10

标签: java android android-studio retrofit2 rx-android

在我的Android应用程序中使用Rxjava与Retrofit一直有问题,在代码实现中一切似乎都很好,但每当我导航到活动/片段时,应用程序崩溃,并显示以下错误消息。

//Error message
java.lang.IllegalArgumentException: Unable to create converter for java.util.List<com.thebestprice.bestprice.model.SearchRequestModel>
        for method DataEndpointService.getStarredRepositories

//端点声明

@GET("users/{user}/starred")
    Observable<List<SearchRequestModel>> getStarredRepositories(@Path("user") String username);

//客户端类

public class DataClient {

private static final String PROJECT_BASE_URL = "https://api.github.com/";
    private static DataClient instance;
    private DataEndpointService queryResultService;


    private DataClient(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

        final Retrofit retrofit = new Retrofit.Builder().baseUrl(PROJECT_BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        queryResultService = retrofit.create(DataEndpointService.class);
    }

    public static DataClient getInstance(){
        if (instance == null){
            instance = new DataClient();
        }
        return instance;
    }

public io.reactivex.Observable<List<SearchRequestModel>> queryForUserRepo(@NonNull String searchRequestModel){
        return queryResultService.getStarredRepositories(searchRequestModel);
    }
}

//片段显示列表

private void queryResultForSearchData(String userName){

        disposable = DataClient.getInstance().
                queryForUserRepo(userName).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Consumer<List<SearchRequestModel>>() {
                              @Override
                              public void accept(List<SearchRequestModel> searchRequestModels) throws Exception {
                                  mShimmerFrameLayout.stopShimmerAnimation();
                                  rvAllSearch.setAdapter(new ResultAdapter(getActivity(), searchRequestModels));
                              }
                          },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {

                            }`enter code here`
                        });
    }

// rxjava的gradle依赖项和compileSdk27

的改进
//For using RxJava
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.12'

    //logging interceptor
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

    //For Using retrofit to do network request
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

不知道我做错了什么,寻找类似的问题,但在我自己的案例中似乎没有帮助

2 个答案:

答案 0 :(得分:0)

使用RxJava的主要观点是避免循环和列表,调用订阅和映射函数,导致Observables管理所有项目。因此,您不需要返回List

只是使用Github API with Rx的一个示例。

public interface GithubService {
    String SERVICE_ENDPOINT = "https://api.github.com";

    @GET("/users/{login}")
    Observable<Github> getUserRx(@Path("login") String login);

    @GET("/users/{login}")
    Github getUser(@Path("login") String login);
}

public class ServiceFactory {

    /**
     * Creates a retrofit service from an arbitrary class (clazz)
     * @param clazz Java interface of the retrofit service
     * @param endPoint REST endpoint url
     * @return retrofit service with defined endpoint
     */
    public static <T> T createRetrofitService(final Class<T> tClass, final String endPoint) {
        final RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endPoint)
                .build();
        T service = restAdapter.create(tClass);

        return service;
    }
}

        // .....
        service = ServiceFactory.createRetrofitService(
                GithubService.class, GithubService.SERVICE_ENDPOINT);

service.getUserRx(login)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .cache()
                    .subscribe(new Subscriber<Github>() {
                        @Override
                        public final void onCompleted() {
                        }

                        @Override
                        public final void onError(Throwable e) {
                            Log.e(LOG, " ErrorRx Default Github" + e.getMessage());
                        }

                        @Override
                        public final void onNext(Github response) {
                            mCardAdapter.addData(response);
                        }
                    });

// .....

答案 1 :(得分:0)

添加GsonConverterFactory时。 签出您使用的Bean(SearchRequestModel)变量,或者@SerializedName(alternate)批注没有相同的变量名。

对我有用