如何在改装POST中发送对象数组?

时间:2015-07-12 17:58:18

标签: android retrofit

服务器期待这样的事情:

special_array = [{param1 = "string1", param2 = "string2"}, {param1 = "string3", param2 = "string4"}];

我需要制作自己的转换器吗?

2 个答案:

答案 0 :(得分:3)

首先创建一个这样的回调接口并传递整个Object类。

 @POST(URL)
 public void newObject(@Body YourObject object, Callback<Boolean> success);

Retrofit默认使用Gson序列化和反序列化JSON。例如,如果您的Object类看起来像这样:

public class YourObject {

@Expose
private String param1;
@Expose
private String param2;

/**
* 
* @return
* The param1
*/
public String getParam1() {
return param1;
}

/**
* 
* @param param1
* The param1
*/
public void setParam1(String param1) {
this.param1 = param1;
}

/**
* 
* @return
* The param2
*/
public String getParam2() {
return param2;
}

/**
* 
* @param param2
* The param2
*/
public void setParam2(String param2) {
this.param2 = param2;
}

}

然后Gson会自动序列化为以下JSON,

[
    {
        "param1": "string1",
        "param2": "string2"
    },
    {
        "param1": "string3",
        "param2": "string4"
    }
]

你们都完成了!

答案 1 :(得分:0)

我只需要构建一个更大的更复杂的对象,并考虑到这两个参数:

ComplexRequestObject complexRequestObject = new ComplexRequestObject();
complexRequestObject.param1 = new SemiComplexObject[]{
    new SemiComplexObject("value1", "valued2")};
complexRequestObject.param2 = "value3";