android - 改造错误应为 BEGIN_ARRAY 但为 BEGIN_OBJECT
问题描述
我尝试使用手机号码获取 Otp,但它显示这样的错误
E/FAILISJERE:java.lang.IllegalStateException:应为 BEGIN_ARRAY,但在第 1 行第 54 列路径 $.data 处为 BEGIN_OBJECT
这是我的网址:= http://192.168.1.105/XXXX/XXXXX/XXXXXX/default/send-otp
请求字段:手机号,姓名
回应是这样的:-
{
"error": false,
"msg": "Otp sent successfully",
"data": {
"otp": 152265
}
}
APIClient.Kt:-
object ApiClient {
private var retrofit: Retrofit? = null
val client: Retrofit
get() {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit!!
}
}
APIInterface.kt:-
interface ApiInterface {
@FormUrlEncoded
@POST("send-otp")
fun GET_OTP(@Field("name") name: String, @Field("mobileNo") mobileNo: String): Call<OTPSendResponse>
}
AppConfig.kt:-
class AppConfig {
companion object {
const val BASE_URL = "http://192.168.1.105/XXXX/XXXXX/XXXXX/default/"
}
}
OtpModel.kt:-
class OtpModel {
constructor(otp: Int) {
this.otp = otp
}
@SerializedName("otp")
var otp: Int = 0
}
OtpSendResponse.kt:-
class OTPSendResponse {
constructor(error: String, data: ArrayList<OtpModel>, msg: String) {
this.error = error
this.data = data
this.msg = msg
}
@SerializedName("error")
var error: String = ""
@SerializedName("msg")
var msg: String = ""
@SerializedName("data")
var data: ArrayList<OtpModel> = ArrayList()
}
MyActivity.kt:-
private fun sendNameAndMobileNum(name: String, mobileNum: String) {
Log.e("MOBILE", "${mobileNum}")
val apiService = ApiClient.client.create(ApiInterface::class.java)
val call = apiService.GET_OTP(name, mobileNum)
call.enqueue(object : Callback<OTPSendResponse> {
override fun onResponse(call: Call<OTPSendResponse>, response: Response<OTPSendResponse>) {
Log.e("OTP", "${response.body()?.data!![0].otp}")
val otpIs = response.body()!!.data[0].otp
val i = Intent(this@AddNumActivity, OTPVerifyActivity::class.java)
i.putExtra("otp", otpIs)
i.putExtra("mobileNum", mobileNum)
startActivity(i)
}
override fun onFailure(call: Call<OTPSendResponse>, t: Throwable) {
Toast.makeText(this@AddNumActivity, "Ooops !!", Toast.LENGTH_SHORT).show()
Log.e("FAILISJERE", "${t.message}")
}
})
}
解决方案
更改模型类,因为在 json 响应中没有任何数组,因此删除 ArrayList 标记
data: ArrayList<OtpModel>
至
data: OtpModel
因为它不是数组
推荐阅读
- java - 如何让我的 android 应用程序的浮动小部件记住它的最后位置?
- java - 在场景生成器中添加动作
- django - Django 可以为此进行复杂的选择查询吗?
- python-3.x - 使用 Flask-Restplus 如何创建 POST api 而不使 URL 与 GET 相同
- javascript - 如何在反应中获取文本区域的值?
- android - 如果点击 FAB 菜单以外的任何位置,如何关闭浮动操作按钮菜单?
- python - 通过增加图形大小来避免 python 散点图中的重叠点
- python - 无法从文件中提取和读取链接的特定部分
- flutter - 飞镖围绕一个数字,但作为一个双重
- java - 如何使用 Bootstrap 从滑块中的 URL 渲染 html 上的图像