问题
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