Retrofit2 issue with posting array

251 Views Asked by At

I'm developing a client app for android and my API requires me to send picture names in ArrayList<String> like:

collection[0] = 15a877ce9f22bc8349cac80565c4bff6.jpg
collection[1] = 25a877ce9f22bc8349cac80565c4bff6.jpg

but when i send it it goes in the form like:

collection[] = 15a877ce9f22bc8349cac80565c4bff6.jpg
collection[] = 25a877ce9f22bc8349cac80565c4bff6.jpg

my retrofit interface:

@Field("collection[]") ArrayList<String> collection);

how can I achieve the requested result?

any help would be appreciated! Thank you!

2

There are 2 best solutions below

3
On

Don't put [] in the @Field name, I don't know exactly why you are doing this but it could be confusing as those are reserved character...

You can use something like this:

// ApiService.java
@FormUrlEncoded
@POST("/api/projectLost")
public void projectMarkLost(
    @Field("apiKey") String apiKey,
    @Field("project_id") int projectId,
    @Field("lost_project_remark") String lostProjectRemark,
    @Field("lost_project_reasons") ArrayList<Integer> lostProjectReasons,
    Callback<JsonObject> cb
);

// Content wish to post
POST content:
apiKey = EzAvFvScs45a2DRI0MktdIDeVRbP59
project_id = 986
remark = testing
details = [detail_1,detail_2]
0
On

I found a solution of using Map to achive a desirable result

@FormUrlEncoded
@POST("user/news")
Call<CreateNews> createNews(
        @Field("text") String text,
        @FieldMap Map<String, String> collection);

and in method:

public void createNews(String text, ArrayList<String> collection, final Callback<CreateNews> callback){
    News createNews = ServiceGenerator.createService(News.class);

    SortedMap fields = new TreeMap<String, String>();

    for (int i = collection.size()-1 ; i >= 0 ; i--) {
        fields.put("collection["+i+"]", collection.get(i));
    }

    Call<CreateNews> call = createNews.createNews(text, fields);
    call.enqueue(callback);