API Request | OkHttp | api request via okhttp with two objects

不打扰是莪最后的温柔 提交于 2020-04-18 05:43:35

问题


im new in API Networking so here comes a question about it.

Best beginning ever, but i had too much code...

the json file i want to parse:

{
   "id":"541.23",
   "username":"exampleUser",
   "links":{
      "TWITTER":null,
      "YOUTUBE":"https://www.youtube.com/user/exampleUser"
      "INSTAGRAM":null,
      "TWITCH":null,
      "MIXER":"https://mixer.com/user/"
      "DISCORD":"DiscordUser#4576"
   }
}

for this code is used okhttp and gson:

class MainActivity : AppCompatActivity() {
    lateinit var playerStats: PlayerStats

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        fun fetchJsonGeneral() {
            val url = "https://my.json.org/json
            val request = Request.Builder().url(url).build()
            val client = OkHttpClient()
            client.newCall(request).enqueue(object : Callback {
                var mainHandler = Handler(this@MainActivity.getMainLooper())
                override fun onResponse(call: Call, response: Response) {
                    mainHandler.post {
                        val body = response.body?.string()
                        if (body == null) return@post
                        println("Body:${body}")

                        val gson = GsonBuilder().create()
                        playerStats = gson.fromJson(body, PlayerStats::class.java)

                        println("PlayerStats: ${playerStats}")
                        textView2.text = playerStats.username



                override fun onFailure(call: Call, e: IOException) {
                    println("API execute failed")
                }
            })
        }

and my class for parse:

class PlayerStats(val username: String  ,
                  val id: Double ,
                  val rank: String ,
                  val online: Boolean)

and now i want to parse the object "links". What do I have to do now?


回答1:


You need to create another class, like

data class PlayerStatsLinks(val TWITTER:String?,
 val YOUTUBE:String?,
 val INSTAGRAM:String?,
 val TWITCH:String?,
 val MIXER:String?,
 val DISCORD:String?)

and update you PlayerStats class

class PlayerStats(val username: String  ,
              val id: Double ,
              val rank: String ,
              val online: Boolean,
              val links: PlayerStatsLinks)


来源:https://stackoverflow.com/questions/60607465/api-request-okhttp-api-request-via-okhttp-with-two-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!