java - 在json数组java中对json对象应用条件
问题描述
我像这样从服务器获取一些 json
"applications": [
{
"packageName": "com.facebook.mlite",
"defaultPermissionPolicy": "PROMPT",
"delegatedScopes": [
"DELEGATED_SCOPE_UNSPECIFIED",
"CERT_INSTALL",
"MANAGED_CONFIGURATIONS",
"BLOCK_UNINSTALL",
"PERMISSION_GRANT",
"PACKAGE_ACCESS",
"ENABLE_SYSTEM_APP"
],
"permissionGrants": [
{
"permission": "tt",
"policy": "PROMPT"
}
],
"disabled": false,
"minimumVersionCode": 0
},
{
"packageName": "com.facebook.mlite",
"defaultPermissionPolicy": "PROMPT",
"delegatedScopes": [
"DELEGATED_SCOPE_UNSPECIFIED",
"CERT_INSTALL",
"MANAGED_CONFIGURATIONS",
"BLOCK_UNINSTALL",
"PERMISSION_GRANT",
"PACKAGE_ACCESS",
"ENABLE_SYSTEM_APP"
],
"permissionGrants": [
{
"permission": "tt",
}
],
}
]
现在有一个 json 数组"application":[]
,其中有几个 json 对象。现在这些对象不一样了。缺少一些 json 对象,例如第一个对象包含installType
但第二个对象没有。现在,如果缺少 json 对象,我想将其添加到 recyclerview 的列表中,我想在我的 pojo 类的 contrustor 中发送空字符串
public Application(String defaultPermissionPolicy, List<String> delegatedScopes, List<com.ariaware.enrolldevice.PolicyPojos.PermissionGrants> permissionGrants, Boolean disabled, String installType, Integer minimumVersionCode, String packageName) {
this.defaultPermissionPolicy = defaultPermissionPolicy;
this.delegatedScopes = delegatedScopes;
PermissionGrants = permissionGrants;
this.disabled = disabled;
this.installType = installType;
this.minimumVersionCode = minimumVersionCode;
this.packageName = packageName;
}
这是我班级的构造函数。现在我将如何遍历 json 数组并检查对象是否存在或不存在然后发送空字符串。我需要检查每个对象
解决方案
您可以实现另一个接受 aJSONObject
作为参数的构造函数并创建对象。optString
如果该字段不存在,则在构造函数内部使用它返回一个空字符串(也接受另一个参数作为备用值)。
public Application(JSONObject jsonObject) {
this.installType = jsonObject.optString("installType");
// example of an array
JSONArray scopes = jsonObject.optJSONArray("delegatedScopes");
this.delegatedScopes = new ArrayList<>();
for (int i = 0; i < scopes.length(); i++)
this.delegatedScopes.add(scopes.optString(i));
//other initialization...
}
最后,您JSONObject
从applications
数组中检索每个。
try {
JSONArray res = data.optJSONArray("applications");
Application[] items = new Application[res.length()];
for (int i = 0; i < res.length(); i++)
items[i] = new Application(res.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
推荐阅读
- git - 如何强制更改的主历史记录基于旧历史记录特征分支?
- ios - 如何在表格的一部分中显示有限的行?
- python - 通过powershell编译python ASCII错误
- android - AOSP android.content.res.Resources$NotFoundException:资源 ID #0x0
- powershell - 循环浏览巨大的 CSV 文件
- python - Paramiko 或 sshtunnel 和 ssh-agent 无需输入密码
- javascript - 使用mapbox gl js,一些建筑物没有出现在3d中,如何解决?
- .net - Windows 在所有情况下以编程方式创建用户
- docker - Gitlab CI:找不到泊坞窗
- linux - MobaXterm:在执行前编辑粘贴的命令