如何解析指定JSON对象在UI上展示F1车手的名与姓?
解析Ergast F1 API并在RecyclerView展示车手姓名
先理清API响应的结构
这个API的JSON层级是嵌套的,车手姓名藏在以下路径里:
- 最外层
MRData→StandingsTable→StandingsLists数组(当前赛季仅1个元素)→DriverStandings数组(每个元素对应一位车手)→Driver对象 →givenName(名)和familyName(姓)
关键结构示例:
{ "MRData": { "StandingsTable": { "StandingsLists": [ { "DriverStandings": [ { "Driver": { "givenName": "Max", "familyName": "Verstappen" } } ] } ] } } }
解析数据(以Retrofit+Gson为例)
先定义对应的数据类,匹配JSON结构:
data class DriverStandingsResponse( val MRData: MRData ) data class MRData( val StandingsTable: StandingsTable ) data class StandingsTable( val StandingsLists: List<StandingsList> ) data class StandingsList( val DriverStandings: List<DriverStanding> ) data class DriverStanding( val Driver: Driver ) data class Driver( val givenName: String, val familyName: String )
然后通过Retrofit请求并提取车手姓名:
// 定义API接口 interface ErgastApi { @GET("current/driverStandings.json") suspend fun getCurrentDriverStandings(): Response<DriverStandingsResponse> } // 请求并处理数据 val api = Retrofit.Builder() .baseUrl("http://ergast.com/api/f1/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(ErgastApi::class.java) // 协程中执行请求 lifecycleScope.launch { val response = api.getCurrentDriverStandings() if (response.isSuccessful) { // 提取拼接后的车手姓名列表 val driverNames = response.body()?.MRData?.StandingsTable?.StandingsLists?.firstOrNull() ?.DriverStandings?.map { "${it.Driver.givenName} ${it.Driver.familyName}" } ?: emptyList() // 传给RecyclerView适配器 recyclerView.adapter = DriverAdapter(driverNames) } }
RecyclerView适配器实现
class DriverAdapter(private val driverNames: List<String>) : RecyclerView.Adapter<DriverAdapter.ViewHolder>() { inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val driverNameTv: TextView = itemView.findViewById(R.id.tv_driver_name) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_driver, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.driverNameTv.text = driverNames[position] } override fun getItemCount() = driverNames.size }
最后给RecyclerView设置布局管理器:
recyclerView.layoutManager = LinearLayoutManager(this)
内容的提问来源于stack exchange,提问作者collapseCorpse
相关产品推荐
相关产品推荐

