最近我不得不向Pocket API for Modify端点发出JSON请求。在他们的网站上,编码的JSON数组应该是这样的:
https://getpocket.com/v3/send?actions=%5B%7B%22action%22%3A%22archive%22%2C%22time%22%3A1348853312%2C%22item_id%22%3A229279689%7D%5D&access_token=[ACCESS_TOKEN]&consumer_key=[CONSUMER_KEY]
我使用Retrofit库,我写的方法是:
@Headers("X-Accept: application/json")
@FormUrlEncoded
@POST("v3/send")
Call<ModifyItem> modify(@Field("actions[]") ArrayList<String> actions,
@Field("access_token") String token,
@Field("consumer_key") String consumerKey);
class ModifyItem {
public ArrayList<Boolean> action_results;
public int status;
}
来自OkHttp的Logging Interceptor中生成的JSON请求:
actions%5B%5D=1689582274&actions%5B%5D=archive&actions%5B%5D=1505667307&access_token=[ACCESS_TOKEN]&consumer_key=[CONSUMER_KEY]
正如您所看到的,请求不是我需要的。当我尝试使用POJO类时,它应该是:
@Headers("X-Accept: application/json")
@FormUrlEncoded
@POST("v3/send")
Call<ModifyItem> modify(@Field("actions[]") ArrayList<Action> actions,
@Field("access_token") String token,
@Field("consumer_key") String consumerKey);
class ModifyItem {
public ArrayList<Boolean> action_results;
public int status;
}
POJO课程:
public class Action implements Serializable {
@SerializedName("action")
@Expose
private String action;
@SerializedName("item_id")
@Expose
private String itemId;
@SerializedName("time")
@Expose
private String time;
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
但是JSON请求是这样的:
actions%5B%5D=com.deyanm.pocketapispike.data.Action%4075efc7d1%5Baction%3Darchive%2CitemId%3D308680025%2Ctime%3D1505669208%5D&access_token=[ACCESS_TOKEN]&consumer_key=[CONSUMER_KEY]
我的问题是,我是如何实现所需的JSON的?感谢
答案 0 :(得分:1)
两件事。首先,您的Action
课程需要适当的toString()
方法。
@Override
public String toString() {
return "{\"action\"=" + action +
",\"item_id\"=" + itemId +
",\"time\"=" + time + "}";
}
其次,actions
字段需要被识别为单个对象,而不是字段列表,因此不要直接使用ArrayList,而是使用其toString()表单
Call<ModifyItem> modify(@Field("actions") String actions,
@Field("access_token") String token,
@Field("consumer_key") String consumerKey);
然后使用modify(actions, token, key)
代替modify(actions.toString(), token, key)
。