2016-06-08 29 views
7

我需要发送一个列表/整数值数组与改造到服务器(通过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 
     ); 

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

我读(例如这里https://stackoverflow.com/a/37254442/1565635),一些写有[]参数类似于数组取得了成功,但只导致所谓年龄[]参数2030。 我也试过使用数组以及带有字符串的列表。同样的问题。一切都直接来自一个条目。

那么我该怎么办?

回答

10

要发送的对象

这是您的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 
}; 
+2

好,但是这将我的对象为身体,但并不像其他领域中的一个“阵列”。或者不是吗? –

+0

查看更新回答 –

+0

完全解决了我的问题(y) –