androidretrofitandroid-networking

Android Retrofit POST ArrayList


Trying to send List<String> to server and have Bad Request Error.

public interface PostReviewApi {
        @FormUrlEncoded
        @POST("/")
        void addReview(@Field("review[place_id]") int placeId, @Field("review[content]") String review,
                       @Field("review[rating]") float rating, @Field("review[tag_list]") List<String> tagsList, Callback<ReviewEntity> callback);
    }

...
    postApi.addReview(mRestaurantId, reviewText, (float) mRating, tagsList, new Callback<ReviewEntity>() {
                @Override
                public void success(ReviewEntity reviewEntity, Response response) {
                }

                @Override
                public void failure(RetrofitError error) {
                }
            });
        }

Make @Field("review[tag_list[]]") doesn't help either


Solution

  • Try using @Body annotation instead of @Field and passing a single ReviewBody object.

    class ReviewBody {
    
        public Review review;
    
        public ReviewBody(int placeId, float rating, String content, List<String> tagList) {
            review = new Review(placeId, rating, content, tagList);
        }
    
        public class Review {
            @SerializedName("place_id")
            public int placeId;
            public float rating; 
            public String content;
            @SerializedName("tag_list")
            public List<String> tagList;
    
            public Review(int placeId, float rating, String content, List<String> tagList) {
                this.placeId = placeId;
                this.rating = rating;
                this.content = content;
                this.tagList = tagList;
            }
        }
    }
    

    @POST("/")
    void addReview(@Body ReviewBody body, Callback<ReviewEntity> callback);
    

    (without @FormUrlEncoded)