如何使用改装在 post 请求中发送多个 json 对象?

How to send multiple json objects in a post request using retrofit?

我有这个 json 键值对对象,需要使用 retrofit

在 post 请求中发送
{
"Criteria":{
  "DisciplineId":0,
  "SeasonId":0,
  "Leagues":[

  ],
  "StartDate":"06 Sep 2013",
  "EndDate":"14 Dec 2013",
  "RoundId":0,
  "GroupId":0,
  "MatchesScores":3
},
"SearchInfo":{
  "PageNumber":1,
  "PageSize":20,
  "Sort":1,
  "TotalRecords":542
 }
}

我正在考虑创建一个与 json 对象的 gson 定义相匹配的 POJO,然后使用 POJO class 中的设置器来设置每个键值对的值。

所以我会有这样的东西

@FormUrlEncoded
@POST("/getMatches")
void getMatches(@Field("Criteria") Criteria criteria,@Field("SearchInfo") SearchInfo searchInfo, Callback<JSONKeys> keys);

我走在正确的轨道上吗?

看到 json 对象中有两个嵌套的 json 对象以及包含其中一个对象的 json 数组,我该如何实现这一点?

您可以创建一个包含这两者的请求 class。只要成员变量的名称匹配 json(或者您使用 SerializedName),转换就会自动发生。

class MyRequest{
    @SerializedName("Criteria") Criteria criteria;
    @SerializedName("SearchInfo") SearchInfo searchInfo;
}

其中 Criteria 是:

class Criteria {
    @SerializedName("DisciplineId")  int disciplineId;
    @SerializedName("SeasonId")      int seasonId;
    @SerializedName("Leagues")       List<Integer> leagues; // Change Integer to datatype
    @SerializedName("StartDate")     String startDate;
    @SerializedName("EndDate")       String endDate;
    @SerializedName("RoundId")       int roundId;
    @SerializedName("GroupId")       int groupId;
    @SerializedName("MatchesScores") int matchesScores;
}

SearchInfo是:

class SearchInfo{
    @SerializedName("PageNumber")   int pageNumber;
    @SerializedName("PageSize")     int pageSize;
    @SerializedName("Sort")         int sort;
    @SerializedName("TotalRecords") int totalRecords;
}

使用尝试(见here):

@POST("/getMatches")
public void getMatches(@Body MyRequest request, Callback<Boolean> success);

Retrofit 在内部使用 Gson,并且会自动将您的 MyRequest 对象转换为您在问题中描述的 json 格式。


注意: 通常习惯将 json 键命名为小写加下划线,java 命名为驼峰式。然后在创建 gson 对象时设置密钥命名约定,而不是到处使用 SerializedName(请参阅 here):

Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create()