当前位置: 首页 > 知识库问答 >
问题:

java.lang.IllegalStateException:应为BEGIN_OBJECT,但为BEGIN_ARRAY Kotlin

汤承允
2023-03-14

我正在尝试使用改版在我的应用程序上实现登录,但是我一直得到这个错误不确定是什么错误,java.lang.IllegalStateException:应该是BEGIN_OBJECT,但应该是BEGIN_ARRAY

这是邮递员的回复

  {
    "isSuccessful": true,
    "message": "successful",
    "user": [
        {
            "id": 1,
            "name": "Raymond Gitonga",
            "email": "xyz@gmail.com",
            "phone": "07222XXXXX"
        }
    ]
}
   data class User(
    val id:Int,
    val name: String,
    val email:String,
    val phone:String
)
  data class LoginResponse(
    val isSuccessful:Boolean,
    val message: String,
    val user: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)
    }
}
  interface RetrofitApi {
    @FormUrlEncoded
    @POST("users/login")
    fun userLogin(
        @Field("email") email:String,
        @Field("password")password:String
    ):Call<LoginResponse>
}

和我的登录类

        login_btn.setOnClickListener {
        val email = email_login.text.toString().trim()
        val password = password_login.text.toString().trim()

        if (email.isEmpty()){
            email_login.error = "Enter email"
            return@setOnClickListener
        }

        if (password.isEmpty()){
            password_login.error = "Enter password"
            return@setOnClickListener
        }

        RetrofitClient.instance.userLogin(email, password)
            .enqueue(object : Callback<LoginResponse> {
                override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                    Toast.makeText(applicationContext, t.message, Toast.LENGTH_LONG).show()
                    println("YESSSSSSSSSSSSS>>>>>>"+t.message)
                }

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

                        SharedPreferenceManager.getInstance(applicationContext).saveUser(response.body()?.user!!)

                        val intent = Intent(applicationContext, MainActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

                        startActivity(intent)

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

            })
    }

共有1个答案

刘选
2023-03-14
val user:User

您的JSON显示的是用户列表,而不是单个用户。将上述改为:

val user: List<User>
 类似资料: