gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:24:00 48 4
gpt4 key购买 nike

我有一个简单的枚举:

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

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

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

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

@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() 用于其他目的。

最佳答案

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

关于android - 如何通过 Retrofit 在 @Query 中传递自定义枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35793344/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com