Android Retrofit + GSON - Enum serialization for A

2019-07-15 04:28发布

This problem (this might be by design, who knows - not simple to find a clear answer, at any rate) occurs in both Android Retrofit 1.9 and 2.0, and with the latest GSON library.

I have an Enum class like such:

public enum SomethingType
{
    @SerializedName("first")
    First,
    @SerializedName("second")
    Second
}

And using Retrofit (2.0, but same issue with 1.9) along with GSON, I attempt to output the enum instance as such:

@Multipart
@POST("things")
Call<ThingResponse> createThing(
        @Part("image") RequestBody image,
        @Part("lat") double lat,
        @Part("lng") double lng,
        @Part("type") SomethingType type);

I was expecting the value transmitted to be first or second.

Instead, something along the way is adding these silly little quotation marks, and the server is receiving values such as "first" or "second".

I've even tried using .registerTypeHierarchyAdapter(Enum.class, new EnumApiSerializer()) in my construction of the Gson object, but then I hit a dead end and gave up (I'm actually sure I could solve the problem this way, but it feels really dirty to have to register a type hierarchy adapter for Enums when I quite clearly defined the SerializedName I wished to use).

So - why the quotation marks? What am I doing wrong, or how can I stop this (unexpected to the uninitiated) behaviour?

Thanks!

EDIT:

Further testing with a JsonSerializer type adapter, I see that with the following code:

Gson gson = new Gson();
String jsonRepresentation = gson.toJson(src);
return new JsonPrimitive(jsonRepresentation);

jsonRepresentation is something like ""first"" (with extra quotes inside). Sure, I can strip them here. But what part of the SerializedName doesn't Gson understand?? :(

EDIT 2:

Looks like @Multipart with Retrofit 2.0 has a much more general problem now: all string arguments have extra quotes added.

Another such issue popped up within the last 24 hours:

Retrofit 2.0-beta-2 is adding literal quotes to MultiPart values

0条回答
登录 后发表回答