首页 > 解决方案 > 从JAVA中的JSON动态读取和存储具有相同起始名称的字段

问题描述

我有一个看起来像这样的 JSON,

{
  "users": [
    {
      "displayName": "Dennis Law",
      "givenName": "Dennis",
      "surname": "Law",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "emailAddress",
          "issuerAssignedId": "dennislaw@gmail.com"
        }
      ],
      "extension_timezone": "VET",
      "extension_locale": "en-IN",
      "extension_tenant": "Team1"
    },
    {
      "displayName": "Shaggy Nate",
      "givenName": "Shaggy",
      "surname": "Nate",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "userName",
          "issuerAssignedId": "Shaggynatealpha"
        }
      ],
      "extension_timezone": "NST",
      "extension_locale": "en-AF",
      "extension_tenant": "Team1"
    }
  ]
}

我编写了一个 java 代码来迭代 JSON 并将值保存在变量中,就像这样,下面是我正在迭代 JSON 的 method() 的内容,所以如果你看到,我有一个包装器users。因此,我将上面提到的 JSON 作为 JSON 对象传递并迭代以获取所有字段,例如 DISPLAYNAME、SURNAME....等等。

JSONObject jsonUserObject = new JSONObject(json_string);
        JSONArray jsonUserArray = jsonUserObject.getJSONArray("users");
    
        for (int i = 0; i < jsonUserArray.length();i++) {
            LOG.info("Iteration...");
            displayName = jsonUserArray.getJSONObject(i).getString("displayName");
            givenName = jsonUserArray.getJSONObject(i).getString("givenName");
            surname = jsonUserArray.getJSONObject(i).getString("surname");
            extension_user_type = jsonUserArray.getJSONObject(i).getString("extension_user_type");

            JSONArray jsonIdentitiesArray = jsonUserArray.getJSONObject(i).getJSONArray("identities");

            for (int j = 0; j < jsonIdentitiesArray.length();j++) {
                signInType = jsonIdentitiesArray.getJSONObject(j).getString("signInType");
                issuerAssignedId = jsonIdentitiesArray.getJSONObject(j).getString("issuerAssignedId");
            }
            try {
                extension_timezone = jsonUserArray.getJSONObject(i).getString("extension_timezone");
                extension_locale = jsonUserArray.getJSONObject(i).getString("extension_locale");
                extension_tenant = jsonUserArray.getJSONObject(i).getString("extension_tenant");
            } catch (JSONException jse) {
                LOG.warn("JSONException occured, some attribute was not found!", jse.getMessage());
                
            }

但是我正在尝试动态执行此操作,如果您看到我有 4 个以开头的字段

extension_ --> 它们是extension_user_typeextension_localextension_timezoneextension_tenant

我不想对这些进行硬编码,我想知道一种我不需要下一行的方法,而是读取所有以extension_开头的字段,然后将其动态存储在变量中,

因为 extension_ 字段可以是这 4 个或者它可以是任何东西,我已经对其进行了硬编码,但我正在寻找一种不对其进行硬编码并动态选择并存储在名为 extension_"blabalbla" 的变量中的方法

提前致谢。

extension_blablabla = jsonUserArray.getJSONObject(i).getString("extension_blablabla");

/////////更新

private static void getData(String userJsonAsStringParam) {
    
        JSONObject jsonUserObject = new JSONObject(userJsonAsStringParam);
        JSONArray jsonUserArray = jsonUserObject.getJSONArray("users");
        
        for (int i = 0; i < jsonUserArray.length();i++) {
            Map<String,String> map = new HashMap<String,String>();
            @SuppressWarnings("unchecked")
            Iterator<String> keys = jsonUserArray.getJSONObject(i).keys();
            while(keys.hasNext()){
                String key = (String)keys.next();
                String value = jsonUserArray.getJSONObject(i).getString(key);
                map.put(key,value);
            }
           
        }  
    }

错误 :

Exception in thread "main" org.json.JSONException: JSONObject["identities"] not a string.

标签: javaarraysjsonjava-11

解决方案


我认为不可能将它们动态地存储在具有相同名称的变量中,例如 extension_timezone。这需要动态更改变量名称,而且您甚至不知道哪些变量存在,哪些不存在。绝对有可能将它们存储在像地图这样的结构中:

Map<String,String> map = new HashMap<String,String>();
Iterator<String> keys = jsonUserArray.getJSONObject(i).keys();
while(keys.hasNext()){
    String nextString = (String)keys.next();
    if(nextString.equals("identities"))
    {
        continue;
    }
    String key = nextString;
    String value = jsonUserArray.getJSONObject(i).getString(key);
    map.put(key,value);
}

变量名称现在用作映射中的键。如果您不知道这里的地图是基本信息:https ://docs.oracle.com/javase/8/docs/api/java/util/Map.html


推荐阅读