Serialize Query-Parameter in Retrofit

前端 未结 4 1965
挽巷
挽巷 2021-02-14 12:17

Imagine the following request:

@POST(\"/recipes/create\")
void createRecipe(@Query(\"recipe\") Recipe recipe, Callback callback);

4条回答
  •  梦毁少年i
    2021-02-14 12:36

    As @Rolf mentioned, there is a way to set customConverter.Factory Example:

        public class QueryConverterFactory extends Converter.Factory {
        public static QueryConverterFactory create() {
            return new QueryConverterFactory();
        }
    
        private QueryConverterFactory() {
        }
    
        @Nullable
        @Override
        public Converter stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            if (type == Date.class) {
                return DateQueryConverter.INSTANCE;
            }
            return null;
        }
    
        private static final class DateQueryConverter implements Converter {
            static final DateQueryConverter INSTANCE = new DateQueryConverter();
    
            private static final ThreadLocal DF = new ThreadLocal() {
                @Override
                public DateFormat initialValue() {
                    return new SimpleDateFormat("yyyy-MM-dd");
                }
            };
    
            @Override
            public String convert(Date date) {
                return DF.get().format(date);
            }
        }
    }
    

    You can add converters for your own types.

提交回复
热议问题