如何用retrofit2 Kotlin解析响应



我无法解析响应。在Swift中,我可以创建一个可编码代码来帮助解析json响应。我是Kotlin的新手,我正在为其他人现有的项目工作。我为字符串和布尔做了一个数据类,但我不知道解析它的语法。请帮忙,谢谢。

responseBody json

{
"bearerToken": "########",
"staySignIn": false
} 

//Interface
interface PostInterface {
class User(
val email: String,
val password: String
)
@POST("signIn")
fun signIn(@Body user: User): Call<ResponseBody>
//Network handler
fun signIn(email: String, password: String): MutableLiveData<Resource> {
val status: MutableLiveData<Resource> = MutableLiveData()
status.value = Resource.loading(null)

val retrofit = ServiceBuilder.buildService(PostInterface::class.java)
retrofit.signIn(PostInterface.User(email, password)).enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
errorMessage(status)
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (response.code() == 200) {
try {
status.value = //how to parse using the model??

} catch (ex: Exception) {
parseError(400, response.body().toString(), status)
}
} else {
//do something...
}
}
})
return status
}
//Model
data class SignInModel(

@field:SerializedName("bearerToken")
val bearerToken: String? = null,

@field:SerializedName("staySignIn")
val staySignIn: Boolean? = null
)
//Storing value class
class RrefManager constructor(var applicationContext: Context) {
private fun getSharedPrefEditor(): sharedPrefEditor.Editor {
return applicationContext.getSharedPrefEditor(prefStorageName, Context.MODE_PRIVATE).edit()
}
public fun setBearerToken(token: String) {
getSharedPrefEditor().putString("bearerToken", token).apply()
}
public fun setStaySignIn(enabled: Boolean) {
getSharedPrefEditor().putBoolean("staySignIn", enabled).apply()
}
}
//SignIn Button
viewModel.signIn().observe(viewLifecycleOwner, androidx.lifecycle.Observer { v ->
if (v.status == Resource.Status.SUCCESS) {   
val model = v.data as SignInModel
pref.setToken(model.token as String) //storing value
pref.setTwoFactorEnabled(model.twoFactorEnabled as Boolean) //storing value
} else if (v.status == Resource.Status.ERROR) {
//do something...
}
})

我认为在swift中实现类似可编码的东西的最佳选择是使用Gson库来解析api响应。

创建改造实例时,将gson转换器传递给构建器,如:

val retrofit = Retrofit.Builder()  
.baseUrl(BaseUrl)  
.addConverterFactory(GsonConverterFactory.create())  
.build() 

完成后,可以让api返回作为数据类的响应,如:

//Interface
interface PostInterface {
@POST("signIn")
fun signIn(@Body user: User): Call<SignInModel>
}

要从类的回调中读取答案,网络调用中的响应已经在回调中解析到模型中。所有的改装回调应该改为接收回调,然后你可以直接访问像状态。Value = response.body()

有关更多信息,您可以参考retrofit库页面,其中给出了如何正确使用它的所有细节和解释。

https://square.github.io/retrofit/

相关内容

  • 没有找到相关文章

最新更新