How can I return String or JSONObject from asynchronous callback using Retrofit?

后端 未结 7 1825
无人及你
无人及你 2020-11-30 00:34

For example, calling

api.getUserName(userId, new Callback() {...});

cause:

retrofit.RetrofitError: retrofit.         


        
7条回答
  •  不知归路
    2020-11-30 00:54

    Retrofit 2.0.0-beta3 adds a converter-scalars module provides a Converter.Factory for converting String, the 8 primitive types, and the 8 boxed primitive types as text/plain bodies. Install this before your normal converter to avoid passing these simple scalars through, for example, a JSON converter.

    So, first add converter-scalars module to build.gradle file for your application.

    dependencies {
        ...
        // use your Retrofit version (requires at minimum 2.0.0-beta3) instead of 2.0.0
        // also do not forget to add other Retrofit module you needed
        compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
    }
    

    Then, create your Retrofit instance like this:

    new Retrofit.Builder()
            .baseUrl(BASE_URL)
            // add the converter-scalars for coverting String
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build()
            .create(Service.class);
    

    Now you can use API declaration like this:

    interface Service {
    
        @GET("/users/{id}/name")
        Call userName(@Path("userId") String userId);
    
        // RxJava version
        @GET("/users/{id}/name")
        Observable userName(@Path("userId") String userId);
    }
    

提交回复
热议问题