Home > Blockchain >  How to Parse Json in Kotlin Using Retrofit?
How to Parse Json in Kotlin Using Retrofit?

Time:11-25

i am new to kotlin and i am in learning phase. I have followed many links but didn't able to understand completely. I want Json response to show in my textview.

Problem: 1 I have tried this code but was unable to get data, but i want to get the items inside data object. Quote and author are coming null.

{
"status": 200,
"message": "Success",
"data": {
    "Quote": "The pain you feel today will be the strength you feel tomorrow.",
    "Author": ""
},
"time": "0.14 s"

}

Problem: 2 I dont know how to parse this response in textview

object ServiceBuilder {

private val client = OkHttpClient.Builder().build()

private val retrofit = Retrofit.Builder()
    .baseUrl("https://fitflex.switchsolutions.com.pk/") // change this IP for testing by your actual machine IP

    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build()

fun<T> buildService(service: Class<T>): T{
    return retrofit.create(service)
}}

RestApi

interface  RestApi{
@Headers("Content-Type: application/json")
@POST("api/getquotes")
abstract fun addUser(@Body userData: UserInfo): Call<UserInfo>}

RestAPiService

class RestApiService
{
    fun addUser(userData: UserInfo, onResult: (UserInfo?) -> Unit)
    {
        val retrofit = ServiceBuilder.buildService(RestApi::class.java)
        retrofit.addUser(userData).enqueue(
            object : Callback<UserInfo>
            {
                override fun onFailure(call: Call<UserInfo>, t: Throwable)
                {
                    onResult(null)
                }

                override fun onResponse( call: Call<UserInfo>, response: Response<UserInfo>)
                {
                    val addedUser = response.body()
                    Log.d("responsee","" addedUser)
                    onResult(addedUser)
                }
            }
        )
    }
}
    

UserInfo

data class UserInfo (

    @SerializedName("Quote")
    val quote : String,

    @SerializedName("Author")
    val author : String
)

MainActivity

 fun getQuotes() {
        val apiService = RestApiService()
        val userInfo = UserInfo("","")

        apiService.addUser(userInfo) {
            Log.d("Error registering user","errter")
            /*if ( != null)
            {
                // it = newly added user parsed as response
                // it?.id = newly added user ID
            } else {
                Log.d("Error registering user","errter")
            }*/
        }
    }

Any help would be appreciated :)

CodePudding user response:

just follow my steps :

File->settings->Plugins

search for JSON To Kotlin class and install it

again click on File->New->Kotlin Data class from JSON

paste your json code here and click on generate. It will generate POJO classes and you will good to go.

CodePudding user response:

The first thing I noticed, is that the data in your json is:

"Quote": "The pain you feel today will be the strength you feel tomorrow.",
"Author": ""

While your UserInfo defined @SerializedName("message") for Quote.

CodePudding user response:

Status, message and data are all part of the response so you need to take care of that. For example this

data class AddUserResponse(
    val `data`: UserInfo, //like you defined it
    val message: String,
    val status: Int,
    val time: String
)

This means parameter and response are different so the RestApi needs to be changed to this

abstract fun addUser(@Body userData: UserInfo): Call<AddUserResponse>}

This in turn also change the types in the service like

class RestApiService
{
    fun addUser(userData: UserInfo, onResult: (UserInfo?) -> Unit)
    {
        val retrofit = ServiceBuilder.buildService(RestApi::class.java)
        retrofit.addUser(userData).enqueue(
            object : Callback<AddUserResponse>
            {
                override fun onFailure(call: Call<AddUserResponse>, t: Throwable)
                {
                    onResult(null)
                }

                override fun onResponse( call: Call<AddUserResponse>, response: Response<AddUserResponse>)
                {
                    val addedUser = response.body()
                    Log.d("responsee","" addedUser)
                    onResult(addedUser.data)
                }
            }
        )
    }
}

now in getQuotes you will have that it is a UserInfo object

    apiService.addUser(userInfo) {
        val returnedUserInfo = it
    }
  • Related