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

vsnjm48y  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(251)

我有一个简单的枚举:

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

从某个版本开始,GSON就能够解析这样的枚举。

final String s = gson.toJson(Season.AUTUMN);

它和我预期的一样工作。输出是"0"。所以,我试着在我的翻新服务中使用它:

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

此外,还添加了日志记录功能,以确保其结果的可靠性:

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

OkHttpClient httpClient = new OkHttpClient.Builder()
        .addInterceptor(httpLoggingInterceptor)
        .build();

但是它失败了。@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);

看起来,它根本不关心枚举。在这些行之前,它测试rawParameterType.isArray()是一个数组或Iterable.class.isAssignableFrom(),仅此而已。
改造示例创建为:

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

gsonGsonBuilder().create()。我看了一下源代码,里面有预定义的ENUM_TypeAdapters.ENUM_FACTORY用于枚举,所以我保持原样。

问题是我可以做些什么,以防止在我的枚举上使用toString()并使用@SerializedName?我将toString()用于其他目的。

hec6srdp

hec6srdp1#

正如@DawidSzydło提到的,我误解了Gson在Retrofit中的用法。它只用于响应/请求解码/编码,而不用于@Query/@Url/@Path e.t.c。对于它们,Retrofit使用Converter.Factory将任何类型转换为String。下面是在将@SerializedName传递给Retrofit服务时自动使用@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;
    }
}

枚举工具:

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;
    }
}

改造创造:

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

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"
    }
}

在日志中,您将看到以下内容:

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

使用的相依性为:

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'
rqenqsqc

rqenqsqc2#

如果不是所有枚举都需要它,我想您也可以跳过Converter.Factory设置,只添加一个toString方法:

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

    override fun toString(): String {
        return javaClass
                .getField(name)
                .getAnnotation(SerializedName::class.java)
                .value
    }
}

或者,如果您需要它用于多个:

val <E : Enum<E>> Enum<E>.serializedName: String
    get() = javaClass
            .getField(name)
            .getAnnotation(SerializedName::class.java)
            .value

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

    override fun toString() = serializedName
}

相关问题