android - 应为 BEGIN_OBJECT,但在第 1 行为 STRING
问题描述
我只是想在使用 Retrofit 访问 API 后显示用户数据。我的 api 响应是:
{"password":"111222333","name":"test name","email":"testem@gmail.com","username":"test1","customer_id":"201060","phone":"0196789"}
但不幸的是,我收到“预期 BEGIN_OBJECT 但在第 1 行第 1 列路径 $ 字符串”错误。
我完全坚持显示我的 json 响应。试了两天。
我的 User.java 类:
public class User {
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("username")
@Expose
private String username;
@SerializedName("customer_id")
@Expose
private String customerId;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("password")
@Expose
private String password;
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getUsername() {
return username;
}
public String getCustomerId() {
return customerId;
}
public String getPhone() {
return phone;
}
public String getPassword() {
return password;
}
}
我的登录类:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://us-central1-gmx-notification.cloudfunctions.net/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
all_api = retrofit.create(allApi.class);
private void getUserDetails(String userName,String passWord){
Call<User> call = all_api.getUserDetails(userName,passWord);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if(!response.isSuccessful()){
Log.d(response.body());
}
else{
User user = response.body();
String content = "";
content+= "Name: "+user.getName()+"\n";
content+= "Email: "+user.getEmail()+"\n";
content+= "Customer ID: "+user.getCustomerId()+"\n";
content+= "Phone: "+user.getPhone()+"\n";
Log.d(content);
}
});
}```
解决方案
该错误是由于您尝试将从 API 响应接收到的字符串输入转换为对象的原因。正如在您的回复中一样,所有键都是字符串类型,因此请确保 bean/POJO 类中所有变量的数据类型必须是字符串。
推荐阅读
- aws-amplify - 连接失败:缓冲区未定义 - 更新到 v4.7.0 后订阅 AWS Amplify (graphql) 订阅时出错
- reactjs - 在 React,js 中遍历 HTMLcollection
- laravel - 在运行时更改包的视图路径
- java - Android仅调用另一个类中的方法的最佳方法
- pandas - 重新索引多索引数据框
- fortran - 动态数组 f95
- android - 如何将视图或自定义参数传递给 GestureDetector?
- kubernetes - 状态 ErrImageNeverPull 无法在 Mac 上设置 kubernetes 仪表板
- ios - 无法将自定义参数放入 Firebase 动态链接
- html - 在节点Js中使用sendFile后如何在html中显示json数组数据