java - 如何在 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"));
然后在我们的TextView
或EditView
我们有null
字符串,而不是什么都没有。
我们可能会null
使用 if-then 语句检查值,但这对于具有如此多字段的实际应用程序来说太过分了。
有没有办法配置JSONObject
优雅地处理null
字符串?
更新:我optString
按照建议使用了后备,但没有效果:
firstName.setText(profileInfo.optString("firstName", ""));
结果是一样EditText
的null
。
解决方案
使用optString
,如果没有找到合适的值,则返回第二个参数而不是异常或null
phone.setText(profileInfo.optString("phone","nophone"));
name.setText(profileInfo.optString("name","noname"));
如果存在,则返回按名称映射的值,如果需要,则强制(尝试强制转换)它,如果不存在此类映射,则回退(返回第二个参数)。
推荐阅读
- spring-boot - Spring Boot 2.2.2 RELEASE - 找不到 PropertySource:无法提取响应
- java - 为什么我们需要 notify() 进行线程间通信
- android - AsyncHttpClient() 完成后如何等待和执行代码?
- reactjs - React-Images 和 React-Photo-Gallery 编译错误
- css - 我试图通过将图像左右浮动来将我的文本包裹在我的图像周围,但没有任何反应
- linux - 关于在Linux中设置环境变量的简单问题
- python - Anaconda Navigator 未在 Windows 10 中启动
- r - 如何通过R中的变量计算疾病流行率
- javascript - 如何根据首次启动设置初始屏幕?
- triggers - Apex 触发器(插入前):在创建新潜在客户记录期间使用自定义查找字段中的值更新公司名称