为啥我的名字和姓氏都为空?

Posted

技术标签:

【中文标题】为啥我的名字和姓氏都为空?【英文标题】:Why i am getting first and last name as null?为什么我的名字和姓氏都为空? 【发布时间】:2021-11-02 11:45:17 【问题描述】:

嗨,我是 API 的初学者,我正在尝试使用改造从 https://reqres.in/api/users?page=2 获取数据我能够成功获取电子邮件和图片,但是名字和姓氏显示为空,为什么?

look at the pic to understand what i am talking about

ActivityForUserBinding binding;
recycle recycle_adapter;
api_interface api;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    binding = ActivityForUserBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    api = Retrofit_instance.get_retrofit_for_users().create(api_interface.class);

    api.get_users(2).enqueue(new Callback<pojo_for_users>() 
        @Override
        public void onResponse(Call<pojo_for_users> call, Response<pojo_for_users> response) 
            if(response.isSuccessful())

                recycle_adapter = new recycle(response.body().getData());
                binding.recycleView.setAdapter(recycle_adapter);

            
        

        @Override
        public void onFailure(Call<pojo_for_users> call, Throwable t) 

        
    );



public class recycle extends RecyclerView.Adapter<recycle.MyViewHolder>

    List<pojo_for_users.Datum> list;

    public recycle(List<pojo_for_users.Datum> list) 
        this.list = list;
    

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 

        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.get_user_profile_holder,parent,false);
        return new MyViewHolder(view);
    

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) 
        holder.firstName.setText(String.valueOf(list.get(position).getFirstName()));
        holder.email.setText(String.valueOf(list.get(position).getEmail()));
        holder.lastName.setText(String.valueOf(list.get(position).getLastName()));
        Glide.with(getApplicationContext()).load(list.get(position).getAvatar()).centerCrop().placeholder(R.drawable.ic_launcher_background).into(holder.userProfile);
    

    @Override
    public int getItemCount() 
        return list.size();
    

    public class MyViewHolder extends RecyclerView.ViewHolder 

        private ImageView userProfile;
        private ConstraintLayout constraintLayout;
        private TextView justText;
        private TextView justTextt;
        private TextView email;
        private TextView lastName;
        private TextView firstName;

        public MyViewHolder(@NonNull View itemView) 
            super(itemView);

            userProfile = (ImageView) itemView.findViewById(R.id.user_profile);
            constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.constraintLayout);
            justText = (TextView) itemView.findViewById(R.id.just_text);
            justTextt = (TextView) itemView.findViewById(R.id.just_textt);
            email = (TextView) itemView.findViewById(R.id.email);
            lastName = (TextView) itemView.findViewById(R.id.last_name);
            firstName = (TextView) itemView.findViewById(R.id.first_name);

        
    

这就是我的 pojo 课

public class pojo_for_users 


private Integer page;

private Integer perPage;

private Integer total;

private Integer totalPages;

private List<Datum> data = null;

private Support support;

private Map<String, Object> additionalProperties = new HashMap<String, Object>();


public Integer getPage() 
    return page;



public void setPage(Integer page) 
    this.page = page;



public Integer getPerPage() 
    return perPage;



public void setPerPage(Integer perPage) 
    this.perPage = perPage;



public Integer getTotal() 
    return total;



public void setTotal(Integer total) 
    this.total = total;



public Integer getTotalPages() 
    return totalPages;



public void setTotalPages(Integer totalPages) 
    this.totalPages = totalPages;



public List<Datum> getData() 
    return data;



public void setData(List<Datum> data) 
    this.data = data;



public Support getSupport() 
    return support;



public void setSupport(Support support) 
    this.support = support;



public Map<String, Object> getAdditionalProperties() 
    return this.additionalProperties;



public void setAdditionalProperty(String name, Object value) 
    this.additionalProperties.put(name, value);


public class Datum 


    private Integer id;

    private String email;

    private String firstName;

    private String lastName;

    private String avatar;

    private Map<String, Object> additionalProperties = new HashMap<String, Object>();


    public Integer getId() 
        return id;
    


    public void setId(Integer id) 
        this.id = id;
    


    public String getEmail() 
        return email;
    


    public void setEmail(String email) 
        this.email = email;
    


    public String getFirstName() 
        return firstName;
    


    public void setFirstName(String firstName) 
        this.firstName = firstName;
    


    public String getLastName() 
        return lastName;
    


    public void setLastName(String lastName) 
        this.lastName = lastName;
    

    public String getAvatar() 
        return avatar;
    


    public void setAvatar(String avatar) 
        this.avatar = avatar;
    


    public Map<String, Object> getAdditionalProperties() 
        return this.additionalProperties;
    


    public void setAdditionalProperty(String name, Object value) 
        this.additionalProperties.put(name, value);
    



public class Support 


    private String url;

    private String text;

    private Map<String, Object> additionalProperties = new HashMap<String, Object>();


    public String getUrl() 
        return url;
    


    public void setUrl(String url) 
        this.url = url;
    


    public String getText() 
        return text;
    


    public void setText(String text) 
        this.text = text;
    


    public Map<String, Object> getAdditionalProperties() 
        return this.additionalProperties;
    


    public void setAdditionalProperty(String name, Object value) 
        this.additionalProperties.put(name, value);
    


创建改造实例

public class Retrofit_instance 


private static Retrofit retrofit;
private static Retrofit retrofit1;
private final static String Base_url = "http://universities.hipolabs.com/";
private final static String Base_url_fo_users = "https://reqres.in/api/";

public static Retrofit get_retrofit()

    if (retrofit == null)
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(Base_url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    

    return retrofit;


public static Retrofit get_retrofit_for_users()

    if (retrofit1 == null)
        retrofit1 = new retrofit2.Retrofit.Builder()
                .baseUrl(Base_url_fo_users)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    

    return retrofit1;

这是我的api接口

public interface api_interface 

@GET("search?")
Call<List<pojo>>getdata(@Query("country") String Country);

@GET("users")
Call<pojo_for_users>get_users(

        @Query("page") int page_number

);

提前致谢。

【问题讨论】:

【参考方案1】:

Retrofit 使用Gson 将原始JSON 转换为Java 对象。转换时,Gson 在您的 Java 类中查找 API 返回的字段名称。

基本上,您必须告诉Gson 映射值的位置。您可以通过两种方式实现这一目标,

    使用准确的 JSON 字段名称命名变量。

    @Expose
    private String first_name;
    
    @Expose
    private String last_name;
    

    请注意,您需要添加@Expose 注释以避免在混淆过程中更改变量名称(当您的build.gradle 中有minifiyEnabled true 时)。

    给变量添加@SerializedName注解。

    @SerializedName("first_name")
    private String firstName;
    
    @SerializedName("last_name")
    private String lastName;
    

【讨论】:

谢谢@Roshana Pitigala 这个解决方案对我有用。继续做好工作。【参考方案2】:

根据您的 JSON 响应,firstName 和 lastName 带有下划线,如下所示。像下面这样更改编码后一切都会好起来的。

private String first_name;

private String last_name;

public String getFirst_name() 
    return first_name;


public void setFirst_name(String first_name) 
    this.first_name = first_name;


public String getLast_name() 
    return last_name;


public void setLast_name(String last_name) 
    this.last_name = last_name;

【讨论】:

谢谢@learner 这个解决方案对我有用。保持良好的工作继续【参考方案3】:

这是因为 pojo_for_users.Datum 类中的属性名称与 API 中的 JSON 属性名称不完全匹配。您需要使用“first_name”而不是“firstName”,以及“last_name”而不是“lastName”。或者您可以使用注释来指定您希望使用的名称和 API 使用的名称:

@SerializedName("last_name") //API uses this
private String lastName;   // but in your code you can use this

【讨论】:

谢谢@GavinWright 这个解决方案对我有用。保持良好的工作继续

以上是关于为啥我的名字和姓氏都为空?的主要内容,如果未能解决你的问题,请参考以下文章

在Woocommerce结帐页面中设置唯一的验证错误通知

我每次进入c++builder,packages的内容都为空,要重新选定,请问各位高手这是为啥

如何从联系信息中获取名字和姓氏?

Android Studio Oracle JDBC,结果集一直为空

如何启用/禁用 HTML5 必填字段验证?

为啥当 == 为空值返回 true 时 >= 返回 false?