android - 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 协程
解决方案
在您之前的问题中,您遇到了一个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>
推荐阅读
- c# - 如何将多个值添加到字典中的一个键并显示重复项?
- android-studio - 如何在 Android Studio (Kotlin) 中共享音频文件?
- android - 自定义 GRPC 客户端存根 - 流未启动
- git - 做了一个 git commit,但由于某种原因,它在 github 上将用户显示为 www
- python - 在python中获取索引og现有索引
- dart - 即使到达 return 语句,函数也会返回 null
- javascript - 部分内容仅在页面刷新后显示
- javascript - 有没有办法有条件地运行脚本?
- c - 使用`ld`链接时出现“未定义的符号引用”错误
- f# - 未调用 FSCheck 收缩器