使用改造无法正确响应错误主体



登录中,实际上我的成功响应在toast上正确显示,但是当键入错误的详细信息时,错误正文响应无法正确显示

这是我的回应-->

{
"status": 401,
"data": false,
"message": "User login unsuccessful.",
"user_msg": "Email or password is wrong. try again"
}

我的以下代码:

override fun onResponse(
call: Call<LoginResponse>,
response: Response<LoginResponse>
) {
var res = response
Log.d("response check ", "" + response.body()?.status.toString())
if (res.body()?.status==200) {
SharedPrefManager.getInstance(applicationContext)
.saveUser(response.body()?.data!!)
val intent = Intent(applicationContext, HomeActivity::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
Toast.makeText(
applicationContext,
res.body()?.message,
Toast.LENGTH_LONG
).show()
Log.d("kjsfgxhufb",response.body()?.status.toString())
startActivity(intent)
finish()

}
else
{
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
applicationContext,
jObjError.getJSONObject("user_msg").getString("message"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
}
}

我的输出在吐司上:

Value Email or password is wrong. try again at user_msg of type java.lang.String cannot be 
converted to JSONObject

其实我不想像这样吐司错误味精。.我想要简单的消息,例如"电子邮件或密码错误。再试一次">

帮帮我谢谢

所以,你试图从"user_msg"获取JSONObject,这是不可能的,因为"user_msg"不是JSONObject,它是一个字符串

JSONObject 看起来像:

"user_msg": {
"message": "Your error"
}

但事实并非如此,您将获得两个不同的字符串值。

"user_msg": "message",
"message" : "another message"

你应该做的是jObjError.getString("user_msg")"user_msg"获取值,另一个jObjError.getString("message")"message"获取值。

最新更新