如何使用Retrofit发送数组/列表

Tob*_*ich 13 android http-post retrofit

我需要将一个列表/一个Integer值数组与Retrofit一起发送到服务器(通过POST)我这样做:

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(
        @Field("age") List<Integer> age
};
Run Code Online (Sandbox Code Playgroud)

并像这样发送:

ArrayList<Integer> ages = new ArrayList<>();
        ages.add(20);
        ages.add(30);

ISearchProfilePost iSearchProfile = gsonServerAPIRetrofit.create(ISearchProfilePost.class);
        Call<ResponseBody> call = iSearchProfile.postSearchProfile(
                ages
        );
Run Code Online (Sandbox Code Playgroud)

问题是,值到达服务器而不是以逗号分隔.所以这里的价值就像年龄:2030而不是年龄:20,30.

我正在阅读(例如这里/sf/answers/26071/​​54442/1565635),有些人通过使用[]编写参数来获得成功,就像一个数组,但只导致名为age []的参数:2030.我也尝试使用Arrays以及带字符串的列表.同样的问题.一切都直接进入一个条目.

那我该怎么办?

小智 17

作为对象发送

这是您的ISearchProfilePost.class

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(@Body ArrayListAge ages);
Run Code Online (Sandbox Code Playgroud)

在这里,您将在pojo类中输入发布数据

public class ArrayListAge{
    @SerializedName("age")
    @Expose
    private ArrayList<String> ages;
    public ArrayListAge(ArrayList<String> ages) {
        this.ages=ages;
    }
}
Run Code Online (Sandbox Code Playgroud)

你的改装电话课

ArrayList<Integer> ages = new ArrayList<>();
        ages.add(20);
        ages.add(30);

ArrayListAge arrayListAge = new ArrayListAge(ages);
ISearchProfilePost iSearchProfile = gsonServerAPIRetrofit.create(ISearchProfilePost.class);
Call<ResponseBody> call = iSearchProfile.postSearchProfile(arrayListAge);
Run Code Online (Sandbox Code Playgroud)

要发送为阵列列表,请选中此链接https://github.com/square/retrofit/issues/1064

你忘了添加 age[]

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(
    @Field("age[]") List<Integer> age
};
Run Code Online (Sandbox Code Playgroud)

  • 好吧,但这会将我的对象作为正文发送,而不是作为其他字段中的"数组".或者不是吗? (2认同)