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

Android 如何为空值设置JSONObject默认字符串,android,json,Android,Json,我使用JSON将数据传递给回收器视图,这非常有效 问题是,我想更改获取的json数据。假设用户不上传配置文件图像,这意味着图像的数据库字段将为空,我们的json不会解析任何数据 因此,如果image==null,我想设置为deafult url字符串 这是我试过的 //traversing through all the object for (int i = 0; i < array.length(); i++) {

我使用JSON将数据传递给回收器视图,这非常有效

问题是,我想更改获取的json数据。假设用户不上传配置文件图像,这意味着图像的数据库字段将为空,我们的json不会解析任何数据

因此,如果image==null,我想设置为deafult 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");
                                }
                            }
//遍历所有对象
对于(int i=0;i
这不起作用,它根本不会改变输出

很明显,我做得不对


请问我该怎么办?实现这一点的最佳方法是什么?

在使用JSON后,您不会将值放回对象中。为避免对象中出现空格/null,建议在初始值设定项中出现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; 
} 
请尝试此代码块

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

json返回null还是空白?您可能需要更改yout,如果是这样,它会同时检查这两个参数,比如if(all.getString(“image”).equals(“”| | all.getString(“image”).equals(null))。这是假设您的json实际上有一个“image”键。好的,谢谢,现在就试试看,图像键是什么意思?就像输出中的图像列一样?只是尝试了一下,但没有效果,我不确定使用.put可能是正确的方法,用于图像的json返回“image”:“”,