首页 > 解决方案 > java.lang.IllegalStateException: 预期 BEGIN_OBJECT 但 BEGIN_ARRAY 改造,kotlin

问题描述

我正在尝试使用 Retrofit 在我的应用程序上实现用户注册,但是我一直收到此错误,不确定是什么问题,java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

这是邮递员的回复

{
"isSuccessful": true,
"message": "successful",
"user": {
    "name": "Jackline Jazz",
    "email": "jackijazz@gmail.com",
    "phone": "000000"
}

}

我有两个模型类用户模型类

data class User(
val name: String,
val email:String,
val phone:String

)

和登录响应类

data class LoginResponse(
val isSuccessful:Boolean,
val message: String,
val user: List<User>

)

我的改造对象

object RetrofitClient {

private const val BASE_URL = "http://10.0.2.2:7000/"

val instance: RetrofitApi by lazy {
    val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

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

}

改造 api

@FormUrlEncoded
@POST("users/register")
fun userRegister(
    @Field("name") name: String,
    @Field("email") email: String,
    @Field("password") password: String,
    @Field("confirmPassword") confirmPassword: String
): Call<LoginResponse>

和我的注册班

RetrofitClient.instance.userRegister(name, email, password, confirmPassword)
            .enqueue(object : Callback<LoginResponse> {
                override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                    Toast.makeText(applicationContext, t.message, Toast.LENGTH_LONG).show()`
                }

                override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
                    if (response.body()?.isSuccessful!!){

                        val intent = Intent(applicationContext, MainActivity::class.java)

                        startActivity(intent)

                    }else{
                        Toast.makeText(applicationContext, response.body()?.message, Toast.LENGTH_LONG).show()
                    }
                }

            })
    }
}

如果可能的话,有人帮我实现 Kotlin 协程

标签: androidkotlinretrofitkotlin-coroutines

解决方案


您之前的问题中,您遇到了一个users/login端点。您创建了一个LoginResponse对来自服务器的响应进行建模的模型。在那里,users/login返回 a List<User>,所以LoginResponse必须这样设置。

现在,您正在users/register到达终点……但您仍在尝试使用LoginResponse. 正如您从 JSON 中看到的那样,您从只有一个用户的服务器获得了不同的 JSON 。因此,您需要一个不同的响应类(例如RegisterResponse)来模拟这个新响应:

data class RegisterResponse(
  val isSuccessful:Boolean,
  val message: String,
  val user: User
)

@FormUrlEncoded
@POST("users/register")
fun userRegister(
    @Field("name") name: String,
    @Field("email") email: String,
    @Field("password") password: String,
    @Field("confirmPassword") confirmPassword: String
): Call<RegisterResponse>

推荐阅读