12

私は AutoValue (および android-apt プラグイン) をプロジェクトで動作させており、AutoValue の Ryan Harter の gson 拡張機能を認識していますが、Retrofit 2 をフックして拡張機能とファクトリ メソッドを抽象クラスで使用するにはどうすればよいですか? ?

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

たとえば、ここでは AutoValue を SignIn JSON モデル オブジェクトで使用して不変性を適用したいと考えていますが、Retrofit (またはより具体的には Gson) を不変の AutoValue モデル クラスに接続するにはどうすればよいでしょうか?

4

2 に答える 2

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);
        }
    }
    
  • Type Adapter Factory を作成します (バージョン > 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 と入力してから autocomplete を入力し、型アダプター コードを生成します。動作させるには、これをライブ テンプレートとして Android Studioに追加する必要があります。

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

ライブ テンプレートの構成

ライブ テンプレートの作成方法と使用方法。

ライブ テンプレート gif

于 2016-04-12T20:41:08.773 に答える
2

Gson TypeAdapterFactory の Jake Wharton による Gist は、Gson での作業が必要なすべての AutoValue クラスに注釈を追加するだけで済み ます https://gist.github.com/JakeWharton/0d67d01badcee0ae7bc9

私にとってはうまくいきます。

ここにもプロガードのヘルプがあります..

-keep class **.AutoValue_*
-keepnames @yourpackage.AutoGson class *
于 2016-09-04T07:52:50.770 に答える