I am trying to use a custom converter for Retrofit
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(BuildConfig.BASE_SER
I would do something like that:
public class StringList extends ArrayList {
// Empty on purpose. The class is here only to be recognized by Gson
}
public class CitationMain {
@SerializedName("field_name_here")
StringList values;
// Your other fields
}
Then when creating the RestAdapter:
public class StringListDeserializer implements JsonDeserializer {
@Override
public StringList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext
context) throws JsonParseException {
StringList value = new StringList();
if (json.isJsonArray()) {
for (JsonElement element : json.getAsJsonArray()) {
value.add(element.getAsString());
}
} else {
value.add(json.getAsString());
}
return value;
}
}
And then:
Gson gson = new GsonBuilder()
.registerTypeAdapter(StringList.class, new StringListDeserializer())
.create();
RestAdapter.Builder builder = new RestAdapter.Builder()
//...
.setConverter(new GsonConverter(gson));
It's not ideal, since the object is custom, but any other solution that I can think of right now is significantly more complex.
The deserializer here is registered specifically for the fields declared as StringList
, and will handle the case of a single string as well as the case of a string array. Any other field type will use the default deserialization process.