MST

星途 面试题库

面试题:Kotlin中Retrofit如何处理不同类型的网络请求响应数据格式

在Kotlin使用Retrofit进行网络请求时,经常会遇到JSON、XML等不同格式的响应数据。请描述如何配置Retrofit,使其能够正确解析JSON和XML格式的数据,并分别给出简单示例代码。
32.6万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

解析JSON数据

  1. 添加依赖: 在build.gradle文件中添加Gson库以及RetrofitGson的转换器依赖:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.6'
  1. 配置Retrofit
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

val gson: Gson = GsonBuilder()
    .setLenient()
    .create()

val retrofit = Retrofit.Builder()
    .baseUrl("https://example.com/api/")
    .addConverterFactory(GsonConverterFactory.create(gson))
    .client(OkHttpClient())
    .build()
  1. 示例代码: 假设响应数据对应的Data类:
data class Data(val id: Int, val name: String)

interface ApiService {
    @GET("data")
    suspend fun getData(): Data
}

val apiService = retrofit.create(ApiService::class.java)

suspend fun main() {
    val response = apiService.getData()
    println(response.name)
}

解析XML数据

  1. 添加依赖: 在build.gradle文件中添加Simple XML库以及RetrofitSimple XML的转换器依赖:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-simplexml:2.9.0'
implementation 'org.simpleframework:simple-xml:2.7.1'
  1. 配置Retrofit
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.simplexml.SimpleXmlConverterFactory

val retrofit = Retrofit.Builder()
    .baseUrl("https://example.com/api/")
    .addConverterFactory(SimpleXmlConverterFactory.create())
    .client(OkHttpClient())
    .build()
  1. 示例代码: 假设响应XML数据对应的Data类:
import org.simpleframework.xml.Element
import org.simpleframework.xml.Root

@Root(name = "data", strict = false)
data class Data(
    @field:Element(name = "id")
    val id: Int,
    @field:Element(name = "name")
    val name: String
)

interface ApiService {
    @GET("data")
    suspend fun getData(): Data
}

val apiService = retrofit.create(ApiService::class.java)

suspend fun main() {
    val response = apiService.getData()
    println(response.name)
}