Serialize Query-Parameter in Retrofit

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

Imagine the following request:

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

4条回答
  •  灰色年华
    2021-02-14 12:37

    I don't think it supports this right now in some nice way. Check this answer by one of the authors: https://github.com/square/retrofit/issues/291

    The suggested method from that answer is to create a custom type that overrides the toString() method, because Retrofit internally uses String.valueOf(value) to convert query or path parameters to strings.

    So, you could have something like this:

    class Recipe {
      public int id;
      public String title;
    
      @Override
      public String toString() {
        // You can use a GSON serialization here if you want
        // This is not a robust implementation
        return Integer.toString(id) + "-" + title;
      }
    }
    

提交回复
热议问题