我正在使用JSON将数据传递给回收器视图,它工作得很好。
问题是,我想要更改获取的json数据。假设用户没有上传个人资料图像,这意味着图像的数据库字段将为空,并且我们的json不会解析任何数据。
因此,如果图像==为空,我希望设置为默认的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");
}
}这不起作用,它根本不会改变输出。
很明显,我没有做好这件事。
我该怎么做呢?实现这一目标的最佳方法是什么?
发布于 2019-06-25 02:01:49
在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;
} https://stackoverflow.com/questions/56741245
复制相似问题