2016-06-08 27 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) –