【发布时间】:2021-09-13 17:32:41
【问题描述】:
我正在使用 Kotlin 制作需要网络通信的 android 应用程序。
我一直无法通过Retrofit2 响应在JSONObject 中检索JSONObject。
首先我创建了一个 JsonObjBase 类,以从 @POST 请求中获取 response.body()。
JsonObjBase
data class JsonObjBase (
@SerializedName("ResultCode") val resultCode : Int,
@SerializedName("ResultValue") val resultValue : String,
@SerializedName("ResultMessage") val resultMessage : String,
@SerializedName("Data") val data : JSONObject
)
还有一个Inteface 用于改造。
interface APICall {
@POST("/api/Login")
fun startLogin(@Body jsonObj: Operator) : Call<JsonObjBase>
companion object {
fun create() : ApiInterface {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(StaticValue.baseUrl)
.build()
return retrofit.create(ApiInterface::class.java)
}
}
}
这是我在 Activity 中提出的改造请求。
活动
val apiInterface = ApiInterface.create().startLogin(opInfo)
apiInterface.enqueue(object : Callback<JsonObjBase> {
override fun onResponse(call: Call<JsonObjBase>, response: Response<JsonObjBase>?) {
if (response?.body() != null) {
// TODO
}
}
override fun onFailure(call: Call<JsonObjBase>, t: Throwable) {
TODO("Not yet implemented")
}
})
int 和 String 值正常接收,但是,我无法检索 "Data"(我想要的形式为 JSONObject。
我只有空的 JSONObject 数据,
{ "ResultCode": 1, "ResultValue": null, "ResultMessage": null, "Data": {} }
如何在响应 JSONObject 中成功检索 JSONObject?
【问题讨论】:
-
你能为
JSONObject添加一些代码吗?也许你是那个任务注释? -
请使用 ROBO pOJO 类生成器从您的 api respopnse 生成数据类。它是一个 android studio 插件,可帮助您防止此类问题。我用它和 gson 一起使用。
-
@GuneshShanbhag 感谢帮助,没想到 ROBOPOJO 会为我制作
Data数据类,真的帮了大忙!