pengwang
pengwang

Reputation: 19956

How to post array parameters with Retrofit?

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?

Upvotes: 5

Views: 10252

Answers (3)

liangroger2007
liangroger2007

Reputation: 21

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);
    }

Upvotes: 2

RealNmae
RealNmae

Reputation: 660

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.

Upvotes: 1

tread
tread

Reputation: 11098

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]", "[email protected]");
values.put("user[password]", "123456");

This answer is copied straight from: Github Retrofit

Upvotes: -2

Related Questions