首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为空值设置JSONObject默认字符串

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

Stack Overflow用户
提问于 2019-06-25 01:19:07
回答 2查看 996关注 0票数 1

我正在使用JSON将数据传递给回收器视图,它工作得很好。

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

因此,如果图像==为空,我希望设置为默认的url字符串

以下是我尝试过的方法

代码语言:javascript
复制
//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");
                                }
                            }

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

很明显,我没有做好这件事。

我该怎么做呢?实现这一目标的最佳方法是什么?

EN

Stack Overflow用户

回答已采纳

发布于 2019-06-25 02:01:49

在JSON中使用.put之后,您不会将值放回对象中,为了避免对象中出现空值/null,建议在初始化器中使用空值时使用默认值。

代码语言:javascript
复制
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
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56741245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档