Home > Software design >  How to send data to server in Retrofit Android
How to send data to server in Retrofit Android

Time:10-16

In my application I want send some data to server with @Body and I used Retrofit library.
In body class I have 2 items, ID and NAME.
When ID is filled, I should send just ID and not send NAME and when NAME is filled, I should send just NAME again not send ID!
Body model is:

data class BodyUserData(
    @SerializedName("types")
    var types: MutableList<Types?>? = null
) {
    data class Types(
        @SerializedName("name")
        var naName: String? = null,
        @SerializedName("id")
        var id: String? = null
    )
}

Api services codes:

@PATCH("update-data")
suspend fun updateUserData(@Header("Authorization") token: String, @Body body: BodyUserData):
        Response<ResponseUserData>

And I write below codes in activity for fill data:

RxBus.listen(RxEvents.TypesListEvent::class.java).subscribe {
    val typesList: MutableList<BodyUserData.Type?> = mutableListOf()
    it.data.forEach { item ->
        if (item.id == 0) {
            typesList.add(BodyUserData.Type(name = item.name))
        } else {
            typesList.add(BodyUserData.Type(id = item.id.toString()))
        }
    }
    body.type = typesList
}

After call Api and see send data in logcat show me body data such as below:

{"types":[{"name":"cars","id":null},{"name":null,"id":"1791538835"},{"name":null,"id":"1812286134"}]}

In above Json send null data but I want when data is null not send to server.
True Json is such as this:

{"types":[{"name":"cars"},{"id":"1791538835"},{"id":"1812286134"}]}

How can I it?

CodePudding user response:

You most remove serializeNulls() from your GsonBuilder that you pass to ConverterFactory of your retrofit so it avoid serialize null values.

CodePudding user response:

You can deal with it using MultipartBody

Api services codes: (paid attention to @Body body : RequestBody)

@PATCH("update-data")
suspend fun updateUserData(@Header("Authorization") token: String, @Body body : RequestBody): Response<ResponseUserData>

In Your activity

RxBus.listen(RxEvents.TypesListEvent::class.java).subscribe {
    val builder = MultipartBody.Builder().apply { setType(MultipartBody.FORM) }
    it.data.forEachIndexed { index, item ->
        if (item.id == 0) {
            builder.addFormDataPart("types[$index][name]", item.name)
        } else {
            builder.addFormDataPart("types[$index][id]", item.id.toString())
        }
    }
    val requestBody = builder.build() // Here you will get request body corresponding to your needs
}
  • Related