如何使用 Retrofit 在 Kotlin 中解析 Json?

How to Parse Json in Kotlin Using Retrofit?

我是 kotlin 新手,正处于学习阶段。我点击了许多链接,但无法完全理解。 我希望 Json 响应显示在我的文本视图中。

问题:1 我试过这段代码但无法获取数据,但我想获取 data 对象中的项目。引用和作者即将失效。

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

}

问题:2 我不知道如何在 textview

中解析此响应
object ServiceBuilder {

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

private val retrofit = Retrofit.Builder()
    .baseUrl("https://url.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)
                }
            }
        )
    }
}
    

用户信息

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")
            }*/
        }
    }

任何帮助将不胜感激:)

只需按照我的步骤操作即可:

File->settings->Plugins

搜索 JSON To Kotlin class 并安装它

再次点击File->New->Kotlin Data class from JSON

在此处粘贴您的 json 代码并点击生成。它将生成 POJO 类,你会很高兴。

我注意到的第一件事是,您 json 中的数据是:

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

虽然您的 UserInfoQuote 定义了 @SerializedName("message")

状态、消息和数据都是响应的一部分,因此您需要注意这些。例如这个

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

这意味着参数和响应不同,因此需要将 RestApi 更改为此

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

这反过来也会改变服务中的类型,例如

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)
                }
            }
        )
    }
}

现在在 getQuotes 中你会得到 it 是一个 UserInfo 对象

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