预期 BEGIN_OBJECT 但在第 1 行第 40 列路径 $.result.loggedUser 处为 NUMBER

Expected BEGIN_OBJECT but was NUMBER at line 1 column 40 path $.result.loggedUser

我正在尝试在 kotlin 中使用 API,这是我第一次使用 API,尤其是改造,我在网上查看了解决方案,但我无法理解如何处理这个。 这是 API link

https://connect.managedcoder.com/api/leaves

为了获得响应,我必须将令牌作为参数的一部分传递,因此 link 必须是:

https://connect.managedcoder.com/api/leaves?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InNoYW5lLnBlcmVpcmFAc2ppbm5vdmF0aW9uLmNvbSIsInBhc3N3b3JkIjoicGFzc3dvcmQxMjMifQ.ncwng1CK8Y2N4z7ZofgB94ZVxJ8V5L8fk1JKGLnNr2s

然而,API 失败并且它 returns 出现上述错误并进入 on failure 方法。 我不确定我在调用 API 时构建 URL 的方式是否正确,如果这是问题的原因,还是由于其他原因。

这是我对 API 的回复:

{
"status": "OK",
"result": {
    "loggedUser": {
        "id": 119,
        "first_name": "Shane",
        "last_name": "Pereira",
        "emp_id": "Goa6",
        "personal_email": "shanepereira30@gmail.com",
        "office_email": "shane.pereira@sjinnovation.com",
        "present_address": "Hno. 172 Church Street Cortalim Goa 403710",
        "permanent_address": "Hno. 172 Church Street Cortalim Goa 403710",
        "mobile_number": "2147483647",
        "alternate_number": "2147483647",
        "emergency_number": "2147483647",
        "country": "India",
        "office_location": "GOA",
        "gender": 1,
        "birth_date": "1970-01-01T00:00:00",
        "maritial_status": null,
        "identity_proof": "",
        "blood_group": "",
        "bank_name": "",
        "bank_account_number": "",
        "salary": null,
        "tax_bracket": "",
        "languages": "",
        "max_qualification": "--",
        "designation_id": 33,
        "shift_type": "09:00 - 18:00",
        "department_id": null,
        "reporting_team": "",
        "reporting_manager": "",
        "reporting_manager_responsibilities": "0",
        "mentor": "",
        "date_of_joining": "2019-01-03T00:00:00",
        "source_of_hire": "",
        "referred_by": "",
        "employment_status": "1",
        "work_phone": "8390429861",
        "employment_type": "full-time",
        "confirmation_date": "2019-06-03T00:00:00",
        "increment_date": "1970-01-01T00:00:00",
        "resignation_date": "1970-01-01T00:00:00",
        "last_working_date": "1970-01-01T00:00:00",
        "notice_period": "2 Months ",
        "reason": "",
        "blacklisted": "",
        "notes": "",
        "knowledge": "--",
        "role_id": 4,
        "is_manager": 0,
        "created": "2019-03-18T11:40:48",
        "modified": "2019-03-18T11:40:48",
        "profile_pic": "",
        "is_pm": 0,
        "hubstaff_name": null
    },
    "error": "No Leave days has been assigned. Please contact with HR.",
    "success": false
}

}

这是我的获取请求

  @GET("api/leaves?")
fun getLeaveData(
   @Query("token")token:String
):Call<LoginResponse>

这是我的改造实例:

object RetrofitClient {
private val  AUTH = "Basic"
private const val  BASE_URL = "https://connect.managedcoder.com/"
private val okHttpClient = OkHttpClient.Builder()
        .addInterceptor{chain ->
            val original = chain.request()
            val RequestBuilder = original.newBuilder()
                .addHeader("Authorization", "")
                .method(original.method(),original.body())
            val request = RequestBuilder.build()
            chain.proceed(request)
        }.build()
val instance: Api by lazy {
    val retrofit= Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttpClient)
        .build()

    retrofit.create(Api::class.java)
}

}

我有 3 个 class,分别是 LoginResponse、Result 和 User LoginResponse 包含响应的结果和状态,结果包含令牌、成功并保存来自用户 class 的已记录用户详细信息,其中包含 ID、姓名和电子邮件

登录响应:

data class LoginResponse ( val status: String, val result:Result) {

}

结果:

data class Result (val token:String, val success: String,val loggedUser: User){

}

用户:

data class User(val id:Int?, val office_email: String?, val first_name: String?)

这里是我调用 API

的地方
    if(token!=""){
    RetrofitClient.instance.getLeaveData(token)
        .enqueue(object :retrofit2.Callback<LoginResponse> {
            override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                Toast.makeText(context,"error"+t.message, Toast.LENGTH_LONG).show()
                Log.d("xxerror response xxxxx", t.message)
            }

            override fun onResponse(
                call: Call<LoginResponse>,
                response: Response<LoginResponse>
            ) {
                // Toast.makeText(context,response.body()?.result?.success, Toast.LENGTH_LONG).show()
                if (response.body()?.status=="OK"){
                    Toast.makeText(context,"mellooooo"+response.body()?.result?.loggedUser?.first_name, Toast.LENGTH_LONG).show()

                }else{
                    Toast.makeText(context,"api failed to load"+response.body()?.status,
                        Toast.LENGTH_LONG).show()
                }

            }

        })
}else{
    Toast.makeText(context,"token is empty",
        Toast.LENGTH_LONG).show()
    val i=  Intent(activity, LoginActivity::class.java)
    startActivity(i)
    SharedPrefManager.getInstance(this.requireContext()).clear()
}

对于上面提供的 GET 请求,下面是响应。

{"status":"OK","result":{"loggedUser":0,"error":"No Leave days has been assigned. Please contact with HR.","success":false}}

可以看到loggedUser0而不是null

当用户模型预期的 success=falseJsonObject 并且响应是 Int 时,因此出现错误。之所以不落入onError块,是因为不是HTTP错误,而是业务逻辑错误。

您可以使用 Gson 手动序列化基于 success 的对象,或者要求服务器发送 null 而不是 0