首页 > 解决方案 > 在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 数组并检查对象是否存在或不存在然后发送空字符串。我需要检查每个对象

标签: javaandroidjson

解决方案


您可以实现另一个接受 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...
}

最后,您JSONObjectapplications数组中检索每个。

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();
}

推荐阅读