API网络中的新功能,因此这里有一个问题。
有史以来最好的开始,但是我的代码太多了...
我要解析的json文件:
{
"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"
}
}
此代码用于okhttp和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([email protected]())
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")
}
})
}
以及我要解析的课程:
class PlayerStats(val username: String ,
val id: Double ,
val rank: String ,
val online: Boolean)
现在,我想解析对象“链接”。我现在该怎么办?
您需要创建另一个类,例如
data class PlayerStatsLinks(val TWITTER:String?,
val YOUTUBE:String?,
val INSTAGRAM:String?,
val TWITCH:String?,
val MIXER:String?,
val DISCORD:String?)
并更新您的PlayerStats
类
class PlayerStats(val username: String ,
val id: Double ,
val rank: String ,
val online: Boolean,
val links: PlayerStatsLinks)