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

How to send Arrays / Lists with Retrofit

提问人:Tobias Reich 提问时间:6/8/2016 最后编辑:CommunityTobias Reich 更新时间:7/5/2023 访问量:35083

问:

我需要将带有 Retrofit 的 Integer 值列表/数组发送到服务器(通过 POST) 我是这样做的:

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

并像这样发送:

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

ISearchProfilePost iSearchProfile = gsonServerAPIRetrofit.create(ISearchProfilePost.class);
        Call<ResponseBody> call = iSearchProfile.postSearchProfile(
                ages
        );

问题是,到达服务器的值不是逗号分隔的。所以那里的值是 age: 2030 而不是 age: 20, 30

我读到(例如,这里 https://stackoverflow.com/a/37254442/1565635)有些人通过像数组一样用 [] 编写参数而取得了成功,但这只会导致名为 age[] : 2030 的参数。 我还尝试使用数组以及带有字符串的列表。同样的问题。一切都直接在一个条目中。

那我能做些什么呢?

Android HTTP-POST 改造

评论

0赞 Rahul 10/31/2020
也检查该解决方案,我正在关注 Gson 以解决类似的问题 stackoverflow.com/a/64621637/12228284

答:

21赞 Panneer Selvam R 6/8/2016 #1

作为对象发送

这是你的 ISearchProfilePost.class

@FormUrlEncoded
@POST("/profile/searchProfile")
Call<ResponseBody> postSearchProfile(@Body ArrayListAge ages);

在这里,您将在 pojo 类中输入帖子数据

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

您的改造呼叫类

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

要以数组列表形式发送,请查看此链接 https://github.com/square/retrofit/issues/1064

您忘记添加age[]

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

评论

4赞 Tobias Reich 6/8/2016
好吧,但这会将我的对象作为主体发送,而不是作为其他字段中的一个“数组”。或者不是吗?
2赞 Goddard 7/3/2019 #2

Retrofit 现在可以做到这一点,至少我用这个 -> 进行了测试implementation 'com.squareup.retrofit2:retrofit:2.1.0'

例如

@FormUrlEncoded
@POST("index.php?action=item")
Call<Reply> updateStartManyItem(@Header("Authorization") String auth_token, @Field("items[]") List<Integer> items, @Field("method") String method);

这就是我们正在研究的作品。

@Field("items[]") List<Integer> items

评论

0赞 Tobias Reich 7/4/2019
当 2.6 已经发布时,您使用“现在”版本 2.1 是否有特定原因?或者这应该意味着“从 2.1 开始工作”?
0赞 Goddard 7/5/2019
正是我测试过的......编辑了答案以包含此详细信息。
0赞 Rakesh Jha 7/5/2023 #3

如果要使用 Retrofit 上传对象数组,请按照以下步骤操作。它将 100% 工作。 就我而言,我有 2 个参数,一个是 userId,第二个是 location_data。在第二个参数中,我必须传递对象数组。

@FormUrlEncoded
@POST("api/send_array_data")
Call<StartResponseModal> postData(@Field("user_id") String user_id,
                                             @Field("location_data") String 
jsonObject);

然后在你的 MainActivity.class / Fragments 中。

 ArrayList<JSONObject> obj_arr;  // define this at top level.
 try {
                JSONArray jsonArray = new JSONArray();
                obj_arr = new ArrayList<>();
                 // LocationData is model class. 
                for (LocationData cart : arrayList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("latitude", cart.getLatitude());
                    jsonObject.put("longitude", cart.getLongitude());
                    jsonObject.put("address", cart.getAddress());
                    jsonObject.put("battery", cart.getBattery());
                    jsonObject.put("is_gps_on", cart.getIs_gps_on());
                    jsonObject.put("is_internet_on", 
                     cart.getIs_internet_on());
                    jsonObject.put("type", cart.getType());
                    jsonObject.put("date_time", cart.getDate_time());
                    jsonArray.put(jsonObject);
                    obj_arr.add(jsonObject);
                }
                Log.e("JSONArray", String.valueOf(jsonArray));
            } catch (JSONException jse) {
                jse.printStackTrace();
            }




 String user_id = SharedPreferenceUtils.getString(getActivity(), 
 Const.USER_ID);
    RetrofitAPI retrofitAPI = 
 APIClient.getRetrofitInstance().create(RetrofitAPI.class);
    Call<StartResponseModal> call = 
 retrofitAPI.postData(user_id,obj_arr.toString());
    call.enqueue(new Callback<StartResponseModal>() {
        @Override
        public void onResponse(Call<StartResponseModal> call, 
  Response<StartResponseModal> response) {
            // Handle success
            if (response.isSuccessful() && 
  response.body().getErrorCode().equals("0")) {
                // Process the response here
                Log.e("Hello Room data send","Success");
                deleteItemsFromDatabase();


            } else {
                // Handle API error
                Log.e("Hello Room data send","failed else");

            }
        }

        @Override
        public void onFailure(Call<StartResponseModal> call, Throwable t) {
            // Handle failure
            Log.e("Hello Room send","failure");

        }
    });