使用 retrofit2 在 json 对象中发布 json 数组时遇到问题

Trouble posting json array within a json object with retrofit2

在 api 中,我必须在 JSonObject 中发送 JSonArrayJSonObject 是这样的:

{
    "token" : "1",
    "task_name" : "Name",
    "task_desc" : "Description",
    "task_start_date" : "2020/10/01",
    "task_end_date" : "2020/10/02",
    "task_award" : "15",
    "child_ids" : [
          {
              "child_id" : "1"
          },
          {
              "child_id" : "2"
          }
      ]
}

当我使用 Postman 发送此请求时,它工作正常并且响应以我想要的方式接收。但是在 android 应用程序中实现它时,我收到一条错误消息:

retrofit2.adapter.rxjava2.httpexception http 500 internal server error

很明显这不是服务器端错误,因为它在 Postman 中运行良好。

这是我用于 api:

的界面
interface CreateTaskRemote {

    @FormUrlEncoded
    @POST("parent_create_task")
    fun createTask(
        @Field("token") parentToken: String,
        @Field("task_name") title: String,
        @Field("task_desc") description: String,
        @Field("task_start_date") startDate: String,
        @Field("task_end_date") endDate: String,
        @Field("task_award") award: String,
        @Field("child_ids") childIds: List<ChildId>     <-- here i'm sending array
    ): Single<BooleanResponse>
}

还有 ChildId class:

data class ChildId(
    @SerializedName("child_id") val id: Int
)

实施 JSON 数组似乎存在错误。但是我在互联网上搜索了很多,但找不到适合我情况的解决方案。

可能是因为您 post 将 child_id 作为整数值,但您应该 post 将其作为字符串。 (关于:"child_id" : "1"

data class ChildId(
    @SerializedName("child_id") val id: String
)

编辑: 也尝试使用此配置:

data class CreateTaskArgs (
    @SerializedName("token") val token : Int,
    @SerializedName("task_name") val taskName : String,
    @SerializedName("task_desc") val taskDesc : String,
    @SerializedName("task_start_date") val taskStartDate : String,
    @SerializedName("task_end_date") val taskEndDate : String,
    @SerializedName("task_award") val taskAward : Int,
    @SerializedName("child_ids") val childIds : List<ChildId>
)
@POST("parent_create_task")
fun createTask(
    @Body args: CreateTaskArgs
): Single<BooleanResponse>