How to iterate over a JSONObject?

后端 未结 16 1860
孤街浪徒
孤街浪徒 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:32

    Below code worked fine for me. Please help me if tuning can be done. This gets all the keys even from the nested JSON objects.

    public static void main(String args[]) {
        String s = ""; // Sample JSON to be parsed
    
        JSONParser parser = new JSONParser();
        JSONObject obj = null;
        try {
            obj = (JSONObject) parser.parse(s);
            @SuppressWarnings("unchecked")
            List<String> parameterKeys = new ArrayList<String>(obj.keySet());
            List<String>  result = null;
            List<String> keys = new ArrayList<>();
            for (String str : parameterKeys) {
                keys.add(str);
                result = this.addNestedKeys(obj, keys, str);
            }
            System.out.println(result.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    public static List<String> addNestedKeys(JSONObject obj, List<String> keys, String key) {
        if (isNestedJsonAnArray(obj.get(key))) {
            JSONArray array = (JSONArray) obj.get(key);
            for (int i = 0; i < array.length(); i++) {
                try {
                    JSONObject arrayObj = (JSONObject) array.get(i);
                    List<String> list = new ArrayList<>(arrayObj.keySet());
                    for (String s : list) {
                        putNestedKeysToList(keys, key, s);
                        addNestedKeys(arrayObj, keys, s);
                    }
                } catch (JSONException e) {
                    LOG.error("", e);
                }
            }
        } else if (isNestedJsonAnObject(obj.get(key))) {
            JSONObject arrayObj = (JSONObject) obj.get(key);
            List<String> nestedKeys = new ArrayList<>(arrayObj.keySet());
            for (String s : nestedKeys) {
                putNestedKeysToList(keys, key, s);
                addNestedKeys(arrayObj, keys, s);
            }
        }
        return keys;
    }
    
    private static void putNestedKeysToList(List<String> keys, String key, String s) {
        if (!keys.contains(key + Constants.JSON_KEY_SPLITTER + s)) {
            keys.add(key + Constants.JSON_KEY_SPLITTER + s);
        }
    }
    
    
    
    private static boolean isNestedJsonAnObject(Object object) {
        boolean bool = false;
        if (object instanceof JSONObject) {
            bool = true;
        }
        return bool;
    }
    
    private static boolean isNestedJsonAnArray(Object object) {
        boolean bool = false;
        if (object instanceof JSONArray) {
            bool = true;
        }
        return bool;
    }
    
    0 讨论(0)
  • 2020-11-22 04:33

    Maybe this will help:

    JSONObject jsonObject = new JSONObject(contents.trim());
    Iterator<String> keys = jsonObject.keys();
    
    while(keys.hasNext()) {
        String key = keys.next();
        if (jsonObject.get(key) instanceof JSONObject) {
              // do something with jsonObject here      
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:34

    First put this somewhere:

    private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return iterator;
            }
        };
    }
    

    Or if you have access to Java8, just this:

    private <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) {
        return () -> iterator;
    }
    

    Then simply iterate over the object's keys and values:

    for (String key : iteratorToIterable(object.keys())) {
        JSONObject entry = object.getJSONObject(key);
        // ...
    
    0 讨论(0)
  • 2020-11-22 04:38

    Can't believe that there is no more simple and secured solution than using an iterator in this answers...

    JSONObject names () method returns a JSONArray of the JSONObject keys, so you can simply walk though it in loop:

    JSONObject object = new JSONObject ();
    JSONArray keys = object.names ();
    
    for (int i = 0; i < keys.length (); i++) {
       
       String key = keys.getString (i); // Here's your key
       String value = object.getString (key); // Here's your value
       
    }
    
    0 讨论(0)
  • 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<String,String> myKeyValues = new HashMap<String,String>();
    
    // Used for constructing the path to the key in the json object
    Stack<String> key_path = new Stack<String>();
    
    // 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();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:39
    Iterator<JSONObject> iterator = jsonObject.values().iterator();
    
    while (iterator.hasNext()) {
     jsonChildObject = iterator.next();
    
     // Do whatever you want with jsonChildObject 
    
      String id = (String) jsonChildObject.get("id");
    }
    
    0 讨论(0)
提交回复
热议问题