2

I am trying to use AutoValue library from here

I have using Retrofit 2.0 for web service call, all web service request getting failed with HTTP Request error 400. By further investigation I got to know that I have to set the TypeAdapterFactory and pass it to Retrofit Builder like

Retrofit retrofit = new Retrofit
    .Builder()
    .addConverterFactory(gsonConverterFactory)
    .baseUrl("http://url.com/")
    .build()

This answer is available at How to use AutoValue with Retrofit 2?

But the gsonConverterFactory being used there is like

public class AutoValueGsonTypeAdapterFactory implements TypeAdapterFactory {

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<? super T> rawType = type.getRawType();

    if (rawType.equals(SignIn.class)) {
        return (TypeAdapter<T>) SignIn.typeAdapter(gson);
    } 

    return null;
}

}

where rawType.equals(SignIn.class) is being used, so my question is, is there any way to make generic version of AutoValueGsonTypeAdapterFactory or I have to create separate AutoValueGsonTypeAdapterFactory for each web service request with respective DTO??

Thanks in advance

Community
  • 1
  • 1
Sandeep Tengale
  • 152
  • 4
  • 13

1 Answers1

0

To generate a TypeAdapterFactory for all of your auto-value-gson classes, simply create an abstract class that implements TypeAdapterFactory and annotate it with @GsonTypeAdapterFactory, and auto-value-gson will create an implementation for you. You simply need to provide a static factory method, just like your AutoValue classes, and you can use the generated TypeAdapterFactory to help Gson de/serialize your types.

from gson extension documentation

Create the below factory method to handle

@GsonTypeAdapterFactory
public abstract class MyAdapterFactory implements TypeAdapterFactory {

  // Static factory method to access the package
  // private generated implementation
  public static TypeAdapterFactory create() {
    return new AutoValueGson_MyAdapterFactory();
  }

}

register an instance of the factory :

GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(
                new GsonBuilder()
                        .registerTypeAdapterFactory(AutoValueGsonTypeAdapterFactory.create())
                        .create());

and then add it to retrofitclient as

Retrofit retrofitClient = new Retrofit.Builder()
                .baseUrl(BuildConfig.END_POINT)
                .addConverterFactory(gsonConverterFactory)
                .client(okHttpClient.build())
                .build();
rahul.ramanujam
  • 5,608
  • 7
  • 34
  • 56