读取并动态存储JAVA中JSON中具有相同起始名称的字段。

huangapple go评论92阅读模式
英文:

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

问题

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>();
        JSONObject userObject = jsonUserArray.getJSONObject(i);

        @SuppressWarnings("unchecked")
        Iterator<String> keys = userObject.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            String value = userObject.getString(key);
            map.put(key, value);
        }
    }
}

Error:

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

I have a JSON which looks like this,

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

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(&quot;users&quot;);
    
        for (int i = 0; i &lt; jsonUserArray.length();i++) {
            LOG.info(&quot;Iteration...&quot;);
            displayName = jsonUserArray.getJSONObject(i).getString(&quot;displayName&quot;);
            givenName = jsonUserArray.getJSONObject(i).getString(&quot;givenName&quot;);
            surname = jsonUserArray.getJSONObject(i).getString(&quot;surname&quot;);
            extension_user_type = jsonUserArray.getJSONObject(i).getString(&quot;extension_user_type&quot;);

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

            for (int j = 0; j &lt; jsonIdentitiesArray.length();j++) {
                signInType = jsonIdentitiesArray.getJSONObject(j).getString(&quot;signInType&quot;);
                issuerAssignedId = jsonIdentitiesArray.getJSONObject(j).getString(&quot;issuerAssignedId&quot;);
            }
            try {
                extension_timezone = jsonUserArray.getJSONObject(i).getString(&quot;extension_timezone&quot;);
                extension_locale = jsonUserArray.getJSONObject(i).getString(&quot;extension_locale&quot;);
                extension_tenant = jsonUserArray.getJSONObject(i).getString(&quot;extension_tenant&quot;);
            } catch (JSONException jse) {
                LOG.warn(&quot;JSONException occured, some attribute was not found!&quot;, 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(&quot;extension_blablabla&quot;);

/////////UPDATE

private static void getData(String userJsonAsStringParam) {
    
        JSONObject jsonUserObject = new JSONObject(userJsonAsStringParam);
        JSONArray jsonUserArray = jsonUserObject.getJSONArray(&quot;users&quot;);
        
        for (int i = 0; i &lt; jsonUserArray.length();i++) {
        	Map&lt;String,String&gt; map = new HashMap&lt;String,String&gt;();
        	@SuppressWarnings(&quot;unchecked&quot;)
			Iterator&lt;String&gt; 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 &quot;main&quot; org.json.JSONException: JSONObject[&quot;identities&quot;] not a string.

答案1

得分: 2

我认为不可能将它们动态存储在具有相同名称(例如extension_timezone)的变量中。这需要动态更改变量名称,而且您甚至不会知道哪些变量存在,哪些不存在。
绝对可能的做法是将它们存储在类似于映射(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);
}

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

英文:

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&lt;String,String&gt; map = new HashMap&lt;String,String&gt;();
Iterator&lt;String&gt; keys = jsonUserArray.getJSONObject(i).keys();
while(keys.hasNext()){
    String nextString = (String)keys.next();
    if(nextString.equals(&quot;identities&quot;))
    {
        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

huangapple
  • 本文由 发表于 2020年10月7日 17:28:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64241136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定