Custom Converter for Retrofit

前端 未结 1 1188
轮回少年
轮回少年 2020-12-19 07:01

I am trying to use a custom converter for Retrofit

 RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(BuildConfig.BASE_SER         


        
1条回答
  •  执笔经年
    2020-12-19 07:49

    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.

    0 讨论(0)
提交回复
热议问题