Retrofit 2 beta-4. Android 6. Unable to create con

2019-08-10 16:52发布

问题:

How to fix it?

Process: www.palchiki.com.palchiki, PID: 2047
java.lang.IllegalArgumentException: Unable to create converter for class www.palchiki.com.palchiki.model.ServiceResponse
for method APIWebService.getServices
at retrofit2.Utils.methodError(Utils.java:154)
at retrofit2.MethodHandler.createResponseConverter(MethodHandler.java:62)
at retrofit2.MethodHandler.create(MethodHandler.java:33)
at retrofit2.Retrofit.loadMethodHandler(Retrofit.java:164)
at retrofit2.Retrofit$1.invoke(Retrofit.java:145)
at java.lang.reflect.Proxy.invoke(Proxy.java:393)
at $Proxy2.getServices(Unknown Source)
at www.palchiki.com.palchiki.fragment.ServiceFragment.onCreateView(ServiceFragment.java:94)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)

I use com.squareup.retrofit2:retrofit:2.0.0-beta4 and com.squareup.retrofit2:converter-gson:2.0.0-beta4

Adapter

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URLWebService)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

Interface

@GET("/integration.php?command=getServices")
Call<ServiceResponse> getServices(@Query("city") String cityId);

回答1:

You have to specify a Converter for the class ServiceResponse in order for gson to serialize/deserialize your class effectively it would go like this

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(ServiceResponse.class, new ServiceResponseJson());
Gson gson = builder.build();

later on, you ll have to provide this gson instance to your gson converter factory like this

....addConverterFactory(GsonConverterFactory.create(gson))

ServiceResponseJson will have to implement JsonDeserializer and/or JsonSerializer



回答2:

There is an isssue when using Retrofit2 in Android M, as mentioned in here

One of solution that working for me is :

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(URLWebService)
        .addConverterFactory(GsonConverterFactory.create(
                               new GsonBuilder()
                               .excludeFieldsWithoutExposeAnnotation()
                               .create()
                            ))
        .client(okHttpClient)
        .build();