Search code examples
kotlinandroid-studioretrofit

What gets pass in the body of a POST call when sending a data class in kotlin Android Studio?


I have this post request using retrofit in kotlin Android Studio

@POST("/registerUser.php")
    suspend fun createPost(
        @Body user: User
    ):Response<User>

The data class User is

data class User(
    //val id: Int?,
    val username:String?,
    val address: String?
)

If I check the content of user

val user = User("Kilo", "Old")
Log.d("TAG", "$user")
RetrofitInstance.api.createPost(user) <----- This makes the @POST

I get

User(username=Kilo, address=Old)

So what do I receive on the server side? Does it convert everything to json or does it just pass User(username=Kilo, address=Old)?


Solution

  • When you send a User object using Retrofit's @Body annotation in a POST request, Retrofit should automatically serialize the User object into a JSON before sending it to the server. In your case, the serialized JSON representation of the User object will look something like this:

    {
        "username": "Kilo",
        "address": "Old"
    }
    

    On the server side, you should receive this JSON data as the request body. You can then parse this JSON data to access the individual fields, such as username and address. The server should automatically be set up to handle incoming JSON data and deserialize it.