2016-04-10 101 views
13

我有AutoValue(和android-apt插件)在一个项目中工作,我意识到Ryan Harter的AutoValue的gson扩展,但是如何将Retrofit 2挂接到使用扩展和工厂方法抽象类?如何使用AutoValue进行改造2?

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

例如,在这里,我想用AutoValue与签到JSON模型对象执行不可改变,但我怎么挂钩改造(或者更具体GSON)的不可变的,AutoValue模型类?

回答

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); 
        } 
    } 
    
  • 创建类型适配器厂(跳过如果使用版本> 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() 
    
  • 做你的要求

  • 享受

苯教我们的活动模板:
在您的autovalue类中,键入avtypeadapter,然后自动完成以生成类型适配器代码。要工作,你需要添加这个作为live template in Android Studio

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

Live template configuration

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

Live template gif

+0

很好的解释,欣赏它。我有大部分的工作,但我无法找到AutoValueGsonTypeAdapterFactory。继续收到此错误 “错误:(40,57)错误:无法找到符号类AutoValueGsonTypeAdapterFactory” – 3xplore

+0

您必须在实现TypeAdapterFactory的抽象类上使用@GsonTypeAdapterFactory。检查它在那里https://github.com/rharter/auto-value-gson#factory –

2

下面是一个GSON TypeAdapterFactory其主旨在于通过杰克沃顿商学院,只是需要你的注释添加到您的所有AutoValue类需要与GSON工作 https://gist.github.com/JakeWharton/0d67d01badcee0ae7bc9

为我的伟大工程。

下面是一些proguard的帮助太..

-keep class **.AutoValue_* 
-keepnames @yourpackage.AutoGson class *