18
19

More than 5 years have passed since last update.

RetrofitのPOST/PUTリクエストのパラメータに配列を渡す

Posted at

Retrofitを使ってPUTリクエストのパラメータに配列を渡す方法です。POSTでも同じです。

間違い

@FormUrlEncoded
@PUT("/tags.json")
void putTags(@Field("tags") List<String> tags,
             Callback<Tag> cb);

このように書くと、配列ではなく1つ目のStringが渡されます。

Processing by TagsController#update as JSON
  Parameters: {"tags"=>"hoge1"}

正解

@FormUrlEncoded
@PUT("/tags.json")
void putTags(@Field("tags[]") List<String> tags,
             Callback<Tag> cb);

@Field アノテーションにつける名前を tags[] に変えれば配列が渡されます。

Processing by TagsController#update as JSON
  Parameters: {"tags"=>["hoge1", "hoge2", "hoge3"]}

おまけ

List<String> ではなく String[] でも動きます。

@FormUrlEncoded
@PUT("/tags.json")
void putTags(@Field("tags[]") String[] tags,
             Callback<Tag> cb);

参考 : Android Retrofit Posting Array

18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19