如何将 AutoValue 与 Retrofit 2 结合使用?

2024-04-06

我已经在一个项目中使用了 AutoValue(和 android-apt 插件),并且我知道 Ryan Harter 的 AutoValue gson 扩展,但是如何连接 Retrofit 2 以在抽象类上使用扩展和工厂方法?

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

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


[更新] 库发生了一些变化,请在此处查看更多信息:https://github.com/rharter/auto-value-gson https://github.com/rharter/auto-value-gson

我能够让它像这样工作。我希望它能帮助你。

  • 导入您的 gradle 应用程序文件

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

  • 使用自动值创建对象:

    @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);
        }
    }
    
  • 创建类型适配器工厂(如果使用版本 > 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;
        }
    }
    
  • 使用 GsonBuilder 创建 Gson 转换器

    GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(
            new GsonBuilder()
                    .registerTypeAdapterFactory(new AutoValueGsonTypeAdapterFactory())
                    .create());
    
  • 将其添加到您的改造构建器中

    Retrofit retrofit = new Retrofit
            .Builder()
            .addConverterFactory(gsonConverterFactory)
            .baseUrl("http://url.com/")
            .build()
    
  • 做你的要求

  • Enjoy

奖金直播模板:
在自动值类中,键入 avtypeadapter,然后自动完成以生成类型适配器代码。要工作,您需要将其添加为Android Studio 中的实时模板 https://www.jetbrains.com/help/idea/2016.1/creating-and-editing-live-templates.html.

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 AutoValue 与 Retrofit 2 结合使用? 的相关文章

随机推荐