我使用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");
}
}
这不起作用,它根本不会改变输出。
很明显我做的不对。
拜托,我该怎么办?实现这一目标的最佳途径是什么?
3条答案
按热度按时间yh2wf1be1#
方法后,不会将值放回对象中。在JSON中,为了避免对象中的空白/null,建议在初始化器中有一个默认值。
kpbpu0082#
试试这个代码块
7uhlpewt3#
可以使用optString
optString方法用于使用默认值检索不存在的键的值,返回的是默认值而不是null。