如何使用 Retrofit 发送 POST 和 json?

How to send POST with json using Retrofit?

我正在纠结如何使用 Retrofit2 发送 POST 和 json。 像这样:

{
    "user_available_id": 702,
    "teacher_id" : 3207,
    "schedule" : [{
                "event_id" : 47533,
                "schedule_time" : "2020-11-30 07:00:00",
                "status" :1
             },
             {
                "event_id" : 47532,
                "schedule_time" : "2020-11-30 06:30:00",
                "status" :1
             }]
}

我想像这样发送 post。我想知道是否可以像那样发送或有其他方式。如果有其他方法,你能告诉我吗?顺便说一句,这是我尝试发送它的方式

CreateSchduleAPI.kt


    @POST("schedule/student-create")
    @Headers("Accept: application/json")
    @SerializedName("data")
    suspend fun createScheduleSesi2(
        @Header("Authorization") token: String?,
        @Body createSchedule: String
    ): Response<ScheduleModel>

和模型 ScheduleModel.kt


@Parcelize
data class ScheduleModel(

    @field:SerializedName("user_available_id")
    var userAvailableId: String? = null,

    @field:SerializedName("schedule")
    var schedule: ArrayList<schedule?>? = null,

    @field:SerializedName("teacher_id")
    var teacherId: String? = null
) : Parcelable

@Parcelize
data class schedule(

    @field:SerializedName("event_id")
    var eventId: String? = null,

    @field:SerializedName("schedule_time")
    var scheduleTime: String? = null,

    @field:SerializedName("status")
    var status: String? = null
) : Parcelable

第一

 private suspend fun getMultiSlotJadwal(id: String, date: String) {

        jamList.clear()
        val networkConfig =
            NetworkConfig().getTeacher().getTeacherScheduleAvailability(token, id, date)

        if (networkConfig.isSuccessful) {

            if (networkConfig.body()!!.availability!!.isEmpty()) {

                binding.rvSlot.visibility = View.GONE
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(
                        this,
                        "Jam tidak tersedia",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            } else {
                for (slot in networkConfig.body()!!.availability!!) {

                    //convert tanggal start ke millis
                    val tanggalSlot = slot!!.start!!.toDate().formatTo("yyyy-MM-dd HH:mm")
                    val tanggalInMillis = convertToMillis(tanggalSlot)

                    //ambil tanggal sekarang
                    val myFormat = "yyyy-MM-dd HH:mm" // format tanggal
                    val calendar = Calendar.getInstance()
                    val time = calendar.time
                    val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
                    val curdate = sdf.format(time) //diconvert ke tanggal local
                    val curDateinMillis = convertToMillis(curdate) // convert ke millis

                    val hasilDate = tanggalInMillis - curDateinMillis
                    val tanggalJam = hasilDate / 3600000 //diubah dari millis ke jam

                    if (tanggalJam >= 6) {
                        jamList.add(slot)
                        val sortJamList = jamList.sortedBy { jamList -> jamList.start }
                        binding.rvSlot.visibility = View.VISIBLE

                        binding.rvSlot.adapter = SlotJamAdapter(sortJamList) {
                            teacher_id = it.teacherId.toString()

                            scheduleModel.teacherId = teacher_id
                            scheduleModel.userAvailableId = user_avalaible_id

                            scheduleItem.scheduleTime = it.start.toString()
                            scheduleItem.status = "1"
                            scheduleItem.eventId = it.id.toString()
                            scheduleList.add(scheduleItem)

                            scheduleModel.schedule = scheduleList

                            itemClicked = true

                            changeBackgroundButtonSesi2()
                        }
                    }

                }
            }

        } else {

            Handler(Looper.getMainLooper()).post {
                Toast.makeText(
                    this,
                    "Jam tidak tersedia",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

第二

 private suspend fun createSchedule2Sesi() {
        val jsonSchedule = Gson().toJson(scheduleModel)

        val networkConfig = NetworkConfig().createSchedule().createScheduleSesi2(
            token,
            jsonSchedule
        )

        try {
            if (networkConfig.isSuccessful) {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(
                        this,
                        "Pembuatan Jadwal Berhasil",
                        Toast.LENGTH_LONG
                    ).show()
                    startActivity(Intent(this, MainActivity::class.java))
                    finish()
                }
            } else {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(
                        this,
                        "Pembuatan Jadwal Gagal, Cek Koneksi",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        }catch (e:Exception){
            Log.e(TAG, "createSchedule2Sesi: ${e.message}", )
        }

    }

提前致谢

Retrofit 允许您使用 Kotlin 对象作为调用的参数。如果您在构建 Retrofit 实例时使用 GsonConverterFactory,它将自行处理 json 序列化。

这将允许您更改端点的定义,如下所示

@POST("schedule/student-create")
suspend fun createScheduleSesi2(
    @Header("Authorization") token: String?,
    @Body createSchedule: ScheduleModel
): Response<ScheduleModel>