如何为空值设置JSONObject默认字符串

p8h8hvxi  于 2023-05-02  发布在  其他
关注(0)|答案(3)|浏览(210)

我使用JSON将数据传递给回收器视图,它工作得很好。
问题是,我想修改获取的json数据。假设用户没有上传个人资料图像,这意味着图像的数据库字段将是空白的,我们的json不会解析任何数据。
所以我想设置为一个deafault url字符串,如果图像==空
这是我试过的

//traversing through all the object
                            for (int i = 0; i < array.length(); i++) {

                                //getting product object from json array
                                JSONObject allTime = array.getJSONObject(i);

                                //adding the product to product list
                                allTimeEarnersList.add(new LeaderProfile(
                                        allTime.getInt("id"),
                                        allTime.getString("image"),
                                        allTime.getString("username"),
                                        allTime.getInt("earnings")
                                ));

                           //My attempt to set a default value
                            if(allTime.getString("image").equals(null)){
                                    allTime.put("image", "https://10.0.0.0/uploads/blank.png");
                                }
                            }

这不起作用,它根本不会改变输出。
很明显我做的不对。
拜托,我该怎么办?实现这一目标的最佳途径是什么?

yh2wf1be

yh2wf1be1#

方法后,不会将值放回对象中。在JSON中,为了避免对象中的空白/null,建议在初始化器中有一个默认值。

public LeaderProfile(int id, String image, String username, int earnings) { 
    this.id = id; 
    if(image.equals("") || image.equals(null) ){ 
        this.image = "defaulturl.png"; 
    }else{ 
        this.image = image; 
    }
    this.username = username; 
    this.earnings = earnings; 
}
kpbpu008

kpbpu0082#

试试这个代码块

if(allTime.getString("image") != null){
//set imageview glide or picasso
}else{
//set image view glide or picasso but R.drawable.empty_avatar
}
7uhlpewt

7uhlpewt3#

可以使用optString

allTime.optString("image", "https://10.0.0.0/uploads/blank.png")

optString方法用于使用默认值检索不存在的键的值,返回的是默认值而不是null。

相关问题