首页 > 解决方案 > 如何在 JSONObject 中处理来自 RESTful API 的“空”字符串?

问题描述

这是一个服务返回,它为我们提供了用户的个人资料信息:

{
   email: 'someone@example.com',
   pictureUrl: 'http://example.com/profile-pictures/somebody.png',
   phone: null,
   name: null
}

现在我们在我们的 android 应用程序中获取这个 JSON,并将其转换为JSONObject模型:

JSONObject profileInfo = new JSONObject(profileInfoJson);

我们将 UI 视图绑定到数据:

email.setText(profileInfo.getString("email"));
phone.setText(profileInfo.getString("phone"));
name.setText(profileInfo.getString("name"));

然后在我们的TextViewEditView我们有null字符串,而不是什么都没有。

我们可能会null使用 if-then 语句检查值,但这对于具有如此多字段的实际应用程序来说太过分了。

有没有办法配置JSONObject优雅地处理null字符串?

更新:我optString按照建议使用了后备,但没有效果:

firstName.setText(profileInfo.optString("firstName", ""));

结果是一样EditTextnull

标签: javaandroidjson

解决方案


使用optString,如果没有找到合适的值,则返回第二个参数而不是异常或null

phone.setText(profileInfo.optString("phone","nophone"));
name.setText(profileInfo.optString("name","noname"));

如果存在,则返回按名称映射的值,如果需要,则强制(尝试强制转换)它,如果不存在此类映射,则回退(返回第二个参数)。


推荐阅读