使用改造没有得到错误主体的正确响应

Not getting proper response of error body using retrofit

登录时,实际上我的成功响应在 toast.but 上正确显示,当输入错误的详细信息时,错误正文响应未正确显示

这是我的回复-->

{
"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

实际上我不想要这样的 toast 错误消息..我想要像 "email or password is wrong. try again"

这样的简单消息

帮帮我谢谢

因此,您正在尝试从 "user_msg" 获取 JSONObject,这是不可能的,因为 "user_msg" 不是 JSONObject,它是一个 String

JSONObject 看起来像:

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

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

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

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