reading and storing fields with same starting name dynamically from JSON in JAVA

106 Views Asked by At

I have a JSON which looks like this,

{
  "users": [
    {
      "displayName": "Dennis Law",
      "givenName": "Dennis",
      "surname": "Law",
      "extension_user_type": "user",
      "identities": [
        {
          "signInType": "emailAddress",
          "issuerAssignedId": "[email protected]"
        }
      ],
      "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"
    }
  ]
}

I wrote a java code to iterate the JSON and save the values in the variable, like this, below is the content of the method() where I am iterating the JSON, so if you see, I have a wrapper users. So I took the JSON which I mentioned above and passed it as a JSON object and iterated to get all the fields like DISPLAYNAME, SURNAME....and so on.

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

But I am trying to dynamically do this, if you see I have 4 fields that starts with

extension_ --> they are extension_user_type, extension_local, extension_timezone, extension_tenant,

I do not want to hard code those, I want to know a way where I do not need below line and instead read all the fields that starts with a extension_ and then store it in a varibale, dynamically,

BECAUSE the extension_ fields can be those 4 or it can be anything, i have hardcoded it, but I am looking for a way to not hardcode it and pick dynamically and store in a varibale named extension_"blabalbla"

Thanks in advance.

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

/////////UPDATE

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

Error :

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

There are 1 best solutions below

1
On

I don't think it is possible to store them dynamcly in variables that have the same name, like extension_timezone. This require to change variable names dynamicly and also you would not even know which variables exist and which not. What is definetly possible is storing them in a Structure like a map:

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

The variable names are now used as keys in the map. If you do not know maps here are the basic infos: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html