如何将AutoValue与Retrofit 2一起使用?

Oll*_*e C 12 android auto-value retrofit2

我有AutoValue(以及android-apt插件)在一个项目中工作,我知道Ryan Harter的AutoValue的gson扩展,但是如何挂起Retrofit 2以在抽象类上使用扩展和工厂方法?

String grantType = "password";
Call<SignIn> signInCall = retrofitApi.signIn(email, password, grantType);
signInCall.enqueue(callback);
Run Code Online (Sandbox Code Playgroud)

例如,我想将AutoValue与SignIn JSON模型对象一起使用以强制实现不变性但是如何将Retrofit(或者更具体地说是Gson)连接到不可变的AutoValue模型类?

Vin*_* D. 26

[更新]图书馆有所改变,请点击此处查看:https://github.com/rharter/auto-value-gson

我能够让它像这样工作.我希望它会对你有所帮助.

  • 导入您的gradle app文件

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

  • 使用autovalue创建对象:

    @AutoValue public abstract class SignIn {    
        @SerializedName("signin_token") public abstract String signinToken();
        @SerializedName("user") public abstract Profile profile();
    
        public static TypeAdapter<SignIn> typeAdapter(Gson gson) {
            return new AutoValue_SignIn.GsonTypeAdapter(gson);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 创建类型适配器工厂(如果使用版本> 0.3.0,请跳过)

    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;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用GsonBuilder创建Gson转换器

    GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(
            new GsonBuilder()
                    .registerTypeAdapterFactory(new AutoValueGsonTypeAdapterFactory())
                    .create());
    
    Run Code Online (Sandbox Code Playgroud)
  • 将其添加到您的改造生成器中

    Retrofit retrofit = new Retrofit
            .Builder()
            .addConverterFactory(gsonConverterFactory)
            .baseUrl("http://url.com/")
            .build()
    
    Run Code Online (Sandbox Code Playgroud)
  • 请你的

  • 请享用

奖励实时模板:
在您的autovalue类中,键入avtypeadapter然后自动完成以生成类型适配器代码.要使用,您需要将其添加为Android Studio中实时模板.

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

实时模板配置

如何创建和使用实时模板.

实时模板gif