How to post array parameters with Retrofit?

夙愿已清 提交于 2020-07-08 11:20:38

问题


I want to post data as follows:

   {
     "user_id":"14545646",
    "list":["4545645","4545645","4545645","4545645"]
   }

I used the following Retrofit method:

interface DeleteOrder {

         @FormUrlEncoded
         @POST("/api/shop/deleteOrder.json")
         void getPoJoDeleteOrder(@Field("user_id") String user_id, @Field("list") String[] list,Callback<PoJoDeleteOrder> callback);

      }

Is this the correct way?


回答1:


if have many user,then use FieldMap.

user[0][email]=&user[0][password]=&user[1][email]=&user[1][password]=

@POST("/user/sign_in")

User login(@FieldMap Map<String,String> fields);

    Map<String,String> fields = new HashMap<>();
    for (int i=0;i<users.size();i++) {
        User user= users.get(i);
        fields.put("user["+i+"][email]",user.email);
        fields.put("user["+i+"][password]",user.password);
    }



回答2:


This way it will send arguments like this

project_id=986&remark=testing&details=detail_1....

If you want to send array in JSON format, you need to add [] to array name.

 @FormUrlEncoded
    @POST("/api/projectLost")
    public void projectMarkLost(
        @Field("project_id") int projectId,
        @Field("lost_project_reasons[]") ArrayList<Integer> lostProjectReasons,
        Callback<JsonObject> cb
    );

That way you can check the array parameter with is_array($arr) and then iterate it. Source link.




回答3:


If the list of query parameters is fixed you can do this:

@POST("/user/sign_in")
User login(
    @Query("user[email]") String email,
    @Query("user[password]") String password);

Otherwise, with the map you'll need to set the full query parameter as the key:

values.put("user[email]", "foo@bar.com");
values.put("user[password]", "123456");

This answer is copied straight from: Github Retrofit



来源:https://stackoverflow.com/questions/27267593/how-to-post-array-parameters-with-retrofit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!