【问题标题】:How to Parse Json in Kotlin Using Retrofit?如何使用 Retrofit 在 Kotlin 中解析 Json?
【发布时间】:2022-01-03 16:24:00
【问题描述】:

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

任何帮助将不胜感激:)

【问题讨论】:

    标签: android json kotlin retrofit2


    【解决方案1】:

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

    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
        }
    

    【讨论】:

    • 好的,谢谢,还有一件事如何在这里调用数据类作为参数 val userInfo = UserInfo()?
    • 你在哪里val addedUser = response.body()addedUser 将是UserInfo 对象。
    • 请检查getQuotes函数,我想在那里调用UserInfo类
    • 啊是的,我误会了。我稍后会更新答案
    • @Khurria_55 检查编辑
    【解决方案2】:

    按照我的步骤来:

    File->settings->Plugins
    

    搜索 JSON To Kotlin class 并安装它

    再次点击File-&gt;New-&gt;Kotlin Data class from JSON

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

    【讨论】:

    • 请再次阅读我的问题。我已经完成了这些课程
    【解决方案3】:

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

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

    虽然您的 UserInfo@SerializedName("message") 定义为 Quote

    【讨论】:

    • 是的,我已经更新了它,但作为回应,引用和作者仍然是空的。
    猜你喜欢
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2021-01-17
    • 2016-01-09
    相关资源
    最近更新 更多