Home > Back-end >  How to send list of string to server in Android
How to send list of string to server in Android

Time:11-08

In my application I want send some data to server and for this I used Retrofit library.
I should send data such as below:

{
  "hours": ["22:05","19:57"]
}

I write below codes for Api services:

@POST("profile")
    suspend fun postSubmitDrug(@Header("Authorization") token: String, @Body body: RequestBody):Response<ProfileData>

And write below codes info fragment for send data to server:

private lateinit var requestBody: RequestBody
var hourMinuteList = mutableListOf<String>()
val multiPart = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("_method", "post")

multiPart.addFormDataPart("hours[]", parentActivity.hourMinuteList.toString())

requestBody = multiPart.build()

But send this list such as below:

{
  "hours": [22:05,19:57]
}

How can I fix it and send list of string to server?

CodePudding user response:

Use com.google.gson, and when you create your retrofitCLient call .addConverterFactory(create(GsonBuilder()))

create data model, ex:

data class RequestBody(
 val hours: ArrayList<String>? = null
)

and just call your endpoint

@POST("profile")
suspend fun postSubmitDrug(@Header("Authorization") token: String, @Body body: RequestBody):Response<ProfileData>

and this is all, gson will automatically serialize your data to json

  • Related