如何通过Retrofit在@Query中传递自定义枚举?

Nex*_*xen 9 rest android gson retrofit retrofit2

我有一个简单的枚举:

public enum Season {
    @SerializedName("0")
    AUTUMN,
    @SerializedName("1")
    SPRING;
}
Run Code Online (Sandbox Code Playgroud)

从某个版本开始,GSON就能够解析这些枚举.为了确保,我这样做了:

final String s = gson.toJson(Season.AUTUMN);
Run Code Online (Sandbox Code Playgroud)

它按我的预期工作.输出是"0".所以,我尝试在我的Retrofit服务中使用它:

@GET("index.php?page[api]=test")
Observable<List<Month>> getMonths(@Query("season_lookup") Season season);
/*...some files later...*/
service.getMonths(Season.AUTUMN);
Run Code Online (Sandbox Code Playgroud)

并且还添加了日志以确定其结果:

HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient httpClient = new OkHttpClient.Builder()
        .addInterceptor(httpLoggingInterceptor)
        .build();
Run Code Online (Sandbox Code Playgroud)

但它失败了.@Query完全忽略@SerializedName并使用.toString(),所以日志显示我.../index.php?page[api]=test&season_lookup=AUTUMN.

我跟踪了Retrofit源并找到了RequestFactoryParser带有行的文件:

Converter<?, String> converter = 
    retrofit.stringConverter(parameterType, parameterAnnotations);
action = new RequestAction.Query<>(name, converter, encoded);
Run Code Online (Sandbox Code Playgroud)

似乎,就像它根本不关心枚举一样.在这些线之前,它被测试rawParameterType.isArray()为一个阵列或Iterable.class.isAssignableFrom()仅此而已.

改造实例创建是:

retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstants.API_ENDPOINT)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
Run Code Online (Sandbox Code Playgroud)

gsonGsonBuilder().create().我偷看了消息来源,其中预定ENUM_TypeAdapters.ENUM_FACTORY了枚举,所以我保持原样.


问题是我该怎么办,以防止 toString() 在我的枚举上使用和使用 @SerializedName?我 toString() 用于其他目的.

Nex*_*xen 19

正如@DawidSzydło所提到的,我误解Gson了Retrofit中的用法.它仅用于响应/请求解码/编码,但不用于@Query/@Url/@Path e.t.c.对于他们来说,Retrofit用于Converter.Factory将任何类型转换为String.下面是使用自动代码@SerializedName为任意值Enum传递改装服务时.

转换器:

public class EnumRetrofitConverterFactory extends Converter.Factory {
    @Override
    public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        Converter<?, String> converter = null;
        if (type instanceof Class && ((Class<?>)type).isEnum()) {
            converter = value -> EnumUtils.GetSerializedNameValue((Enum) value);
        }
        return converter;
    }
}
Run Code Online (Sandbox Code Playgroud)

EnumUtils:

public class EnumUtils {
    @Nullable
    static public <E extends Enum<E>> String GetSerializedNameValue(E e) {
        String value = null;
        try {
            value = e.getClass().getField(e.name()).getAnnotation(SerializedName.class).value();
        } catch (NoSuchFieldException exception) {
            exception.printStackTrace();
        }
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

改造创造:

retrofit = new Retrofit.Builder()
        .baseUrl(ApiConstants.API_ENDPOINT)
        .client(httpClient)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .addConverterFactory(new EnumRetrofitConverterFactory())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();
Run Code Online (Sandbox Code Playgroud)

08.18更新添加kotlin类似物:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        val httpClient = OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build()

        val gson = GsonBuilder().create()

        val retrofit = Retrofit.Builder()
                .baseUrl(Api.ENDPOINT)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addConverterFactory(EnumConverterFactory())
                .build()

        val service = retrofit.create(Api::class.java)
        service.getMonths(Season.AUTUMN).enqueue(object : Callback<List<String>> {
            override fun onFailure(call: Call<List<String>>?, t: Throwable?) {
                /* ignore */
            }

            override fun onResponse(call: Call<List<String>>?, response: Response<List<String>>?) {
                /* ignore */
            }
        })
    }
}

class EnumConverterFactory : Converter.Factory() {
    override fun stringConverter(type: Type?, annotations: Array<out Annotation>?,
                                 retrofit: Retrofit?): Converter<*, String>? {
        if (type is Class<*> && type.isEnum) {
            return Converter<Any?, String> { value -> getSerializedNameValue(value as Enum<*>) }
        }
        return null
    }
}

fun <E : Enum<*>> getSerializedNameValue(e: E): String {
    try {
        return e.javaClass.getField(e.name).getAnnotation(SerializedName::class.java).value
    } catch (exception: NoSuchFieldException) {
        exception.printStackTrace()
    }

    return ""
}

enum class Season {
    @SerializedName("0")
    AUTUMN,
    @SerializedName("1")
    SPRING
}

interface Api {
    @GET("index.php?page[api]=test")
    fun getMonths(@Query("season_lookup") season: Season): Call<List<String>>

    companion object {
        const val ENDPOINT = "http://127.0.0.1"
    }
}
Run Code Online (Sandbox Code Playgroud)

在日志中,您将看到:

D/OkHttp: --> GET http://127.0.0.1/index.php?page[api]=test&season_lookup=0 
D/OkHttp: --> END GET 
D/OkHttp: <-- HTTP FAILED: java.net.ConnectException: Failed to connect to /127.0.0.1:80
Run Code Online (Sandbox Code Playgroud)

使用的依赖项是:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Run Code Online (Sandbox Code Playgroud)

  • 看起来很好,但如果你想在其他请求中使用没有序列化名称注释的枚举,它将失败.基本上会有快速解决方法:在helper类的catch中,如果没有使用注释,则应将值值设置为枚举值. (3认同)
  • @SherazAhmadKhilji,将java转换为kotlin实际上非常简单,但你有一个观点.科特林时代已经到来.我会补充一点 (2认同)