2016-04-10 4 views
13

AutoValue(android-aptプラグイン)がプロジェクトで働いていて、AutoValueのRyan Harterのgson拡張機能を認識していますが、Retrofit 2を拡張機能とファクトリメソッドを使用して抽象クラス?Retrofit 2でAutoValueを使用するには?

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

例えば、ここで私は不変、自動入力値モデルクラスに不変性を強制するのではなく、どのように私は改修を引っ掛けるか(あるいはより具体的にGson)サインインJSONモデルオブジェクトを自動入力値を使用したいですか?

答えて

26

[更新]ライブラリーは、よりここでチェックし、少し変更されています。私はそれがこのように動作させることができました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; 
        } 
    } 
    
  • リクエスト

ボンをお楽しみくださいあなたの換装ビルダーに

Retrofit retrofit = new Retrofit 
     .Builder() 
     .addConverterFactory(gsonConverterFactory) 
     .baseUrl("http://url.com/") 
     .build() 
  • それを追加します。あなたのGsonBuilder

    GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(
         new GsonBuilder() 
           .registerTypeAdapterFactory(new AutoValueGsonTypeAdapterFactory()) 
           .create()); 
    
  • であなたのGsonコンバータを作成します。私たちのライブテンプレート:
    あなたの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 https://gist.github.com/JakeWharton/0d67d01badcee0ae7bc9

    での作業が必要ですあなたの自動入力値クラスのすべてに注釈を追加する必要がGson TypeAdapterFactoryためのジェイク・ウォートンによって骨子です。

    はここに...あまりにもいくつかのProGuardのヘルプです

    -keep class **.AutoValue_* 
    -keepnames @yourpackage.AutoGson class * 
    
    関連する問題