首页 > 解决方案 > 应为 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);
              }
});
}```

标签: androidretrofit2

解决方案


该错误是由于您尝试将从 API 响应接收到的字符串输入转换为对象的原因。正如在您的回复中一样,所有键都是字符串类型,因此请确保 bean/POJO 类中所有变量的数据类型必须是字符串。


推荐阅读