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

时间:2019-06-24 17:19:06

标签: android json

我正在使用JSON将数据传递到回收者视图,该方法非常有效。

问题是这样的,我想更改获取的json数据。假设用户没有上传个人资料图片,这意味着图片的数据库字段为空白,而我们的json不会解析任何数据作为数据。

因此,如果图像== null,我想设置为默认的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");
                                }
                            }

这不起作用,它根本不会改变输出。

很明显,我没有正确执行这项操作。

请问我该如何处理?实现此目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

在JSON中使用.put之后,请勿将值放回对象中,为避免在对象中出现空格/空值,建议在初始化程序中为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; 
} 

答案 1 :(得分:0)

尝试此代码块

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