How to iterate over a JSONObject?

后端 未结 16 1890
孤街浪徒
孤街浪徒 2020-11-22 04:17

I use a JSON library called JSONObject (I don\'t mind switching if I need to).

I know how to iterate over JSONArrays, but when I parse JSO

16条回答
  •  自闭症患者
    2020-11-22 04:38

    I made a small recursive function that goes through the entire json object and saves the key path and its value.

    // My stored keys and values from the json object
    HashMap myKeyValues = new HashMap();
    
    // Used for constructing the path to the key in the json object
    Stack key_path = new Stack();
    
    // Recursive function that goes through a json object and stores 
    // its key and values in the hashmap 
    private void loadJson(JSONObject json){
        Iterator json_keys = json.keys();
    
        while( json_keys.hasNext() ){
            String json_key = (String)json_keys.next();
    
            try{
                key_path.push(json_key);
                loadJson(json.getJSONObject(json_key));
           }catch (JSONException e){
               // Build the path to the key
               String key = "";
               for(String sub_key: key_path){
                   key += sub_key+".";
               }
               key = key.substring(0,key.length()-1);
    
               System.out.println(key+": "+json.getString(json_key));
               key_path.pop();
               myKeyValues.put(key, json.getString(json_key));
            }
        }
        if(key_path.size() > 0){
            key_path.pop();
        }
    }
    

提交回复
热议问题