How to use AutoValue with Retrofit 2?

前端 未结 2 739
感情败类
感情败类 2021-02-04 11:11

I\'ve got AutoValue (and the android-apt plugin) working in a project, and I\'m aware of Ryan Harter\'s gson extension for AutoValue, but how do I hook Retrofit 2 up to use the

2条回答
  •  抹茶落季
    2021-02-04 11:28

    [update] The library have changed a bit, check more here: https://github.com/rharter/auto-value-gson

    I was able to make it work like this. I hope it will help you.

    • Import in your gradle app file

      apt 'com.ryanharter.auto.value:auto-value-gson:0.3.1'

    • Create object with autovalue:

      @AutoValue public abstract class SignIn {    
          @SerializedName("signin_token") public abstract String signinToken();
          @SerializedName("user") public abstract Profile profile();
      
          public static TypeAdapter typeAdapter(Gson gson) {
              return new AutoValue_SignIn.GsonTypeAdapter(gson);
          }
      }
      
    • Create your Type Adapter Factory (Skip if using version > 0.3.0)

      public class AutoValueGsonTypeAdapterFactory implements TypeAdapterFactory {
      
          public  TypeAdapter create(Gson gson, TypeToken type) {
              Class rawType = type.getRawType();
      
              if (rawType.equals(SignIn.class)) {
                  return (TypeAdapter) SignIn.typeAdapter(gson);
              } 
      
              return null;
          }
      }
      
    • Create your Gson converter with your GsonBuilder

      GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(
              new GsonBuilder()
                      .registerTypeAdapterFactory(new AutoValueGsonTypeAdapterFactory())
                      .create());
      
    • Add it to your retrofit builder

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

    • Enjoy

    Bonus live template:
    In your autovalue class, type avtypeadapter then autocomplete to generate the type adapter code. To work you need to add this as a live template in Android Studio.

    public static TypeAdapter<$class$> typeAdapter(Gson gson) {
        return new AutoValue_$class$.GsonTypeAdapter(gson);
    }
    

    How to create and use the live template.

提交回复
热议问题