我有一個簡單枚舉:如何通過改進在@Query中傳遞自定義枚舉?
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
。
我追查改造來源,發現文件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();
gson
是GsonBuilder().create()
。我在源代碼中偷看,其中預定義了ENUM_TypeAdapters.ENUM_FACTORY
用於枚舉,所以我將它保留原樣。
的問題是,我能做些什麼,以防止使用我枚舉toString()
和使用@SerializedName
?我使用toString()
用於其他目的。
你有適當的轉換器添加到您的改造? https://github.com/square/retrofit/tree/master/retrofit-converters –
似乎Retrofit使用Gson,而序列化
,但不是 ,因爲與 它是序列化的正確方式。 –@DawidSzydło,但是有沒有什麼辦法可以像'Enum >'這樣的轉換器?我想在'@ SerializedName'中使用反射 – Nexen