首页 文章

如何迭代JSONObject?

提问于
浏览 216
250

我使用一个名为 JSONObject 的JSON库(如果需要,我不介意切换) .

我知道如何迭代 JSONArrays ,但是当我解析来自Facebook的JSON数据时,我没有得到一个数组,只有 JSONObject ,但我需要能够通过其索引访问一个项目,例如 JSONObject[0] 以获得第一个,我无法弄清楚该怎么做 .

{
   "http://http://url.com/": {
      "id": "http://http://url.com//"
   },
   "http://url2.co/": {
      "id": "http://url2.com//",
      "shares": 16
   }
   ,
   "http://url3.com/": {
      "id": "http://url3.com//",
      "shares": 16
   }
}

11 回答

  • 510
    Iterator<JSONObject> iterator = jsonObject.values().iterator();
    
    while (iterator.hasNext()) {
     jsonChildObject = iterator.next();
    
     // Do whatever you want with jsonChildObject 
    
      String id = (String) jsonChildObject.get("id");
    }
    
  • 73

    无法相信没有比使用迭代器更简单和安全的解决方案......

    JSONObject names () 方法返回JSONObject键的JSONArray,因此您只需循环遍历它:

    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
    
    }
    
  • 36

    使用Java 8和lambda,更清洁:

    JSONObject jObject = new JSONObject(contents.trim());
    
    jObject.keys().forEachRemaining(k ->
    {
    
    });
    

    https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#forEachRemaining-java.util.function.Consumer-

  • 14

    我会避免使用迭代器,因为它们可以在迭代期间添加/删除对象,也可以使用for循环来清理代码 . 少线简单代码 .

    import org.json.simple.JSONObject;
    public static void printJsonObject(JSONObject jsonObj) {
        for (Object key : jsonObj.keySet()) {
            //based on you key types
            String keyStr = (String)key;
            Object keyvalue = jsonObj.get(keyStr);
    
            //Print key and value
            System.out.println("key: "+ keyStr + " value: " + keyvalue);
    
            //for nested objects iteration if required
            if (keyvalue instanceof JSONObject)
                printJsonObject((JSONObject)keyvalue);
        }
    }
    
  • 13

    对于我的情况,我发现迭代 names() 运作良好

    for(int i = 0; i<jobject.names().length(); i++){
        Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
    }
    
  • 6

    也许这会有所帮助:

    jsonObject = new JSONObject(contents.trim());
    Iterator<String> keys = jsonObject.keys();
    
    while(keys.hasNext()) {
        String key = keys.next();
        if (jObject.get(key) instanceof JSONObject) {
    
        }
    }
    
  • 5

    org.json.JSONObject现在有一个keySet()方法,它返回一个 Set<String> ,可以很容易地通过for-each循环 .

    for(String key : jsonObject.keySet())
    
  • 3

    我曾经有一个json,它需要增加一个id,因为它们是0索引的并且破坏了Mysql自动增量 .

    因此,对于我编写此代码的每个对象 - 可能对某人有帮助:

    public static void  incrementValue(JSONObject obj, List<String> keysToIncrementValue) {
            Set<String> keys = obj.keySet();
            for (String key : keys) {
                Object ob = obj.get(key);
    
                if (keysToIncrementValue.contains(key)) {
                    obj.put(key, (Integer)obj.get(key) + 1);
                }
    
                if (ob instanceof JSONObject) {
                    incrementValue((JSONObject) ob, keysToIncrementValue);
                }
                else if (ob instanceof JSONArray) {
                    JSONArray arr = (JSONArray) ob;
                    for (int i=0; i < arr.length(); i++) {
                        Object arrObj = arr.get(0);
                        if (arrObj instanceof JSONObject) {
                            incrementValue((JSONObject) arrObj, keysToIncrementValue);
                        }
                    }
                }
            }
        }
    

    用法:

    JSONObject object = ....
    incrementValue(object, Arrays.asList("id", "product_id", "category_id", "customer_id"));
    

    这可以转换为适用于JSONArray作为父对象

  • 1

    首先把它放在某个地方:

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

    或者,如果您可以访问Java8,只需:

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

    然后简单地遍历对象的键和值:

    for (String key : iteratorToIterable(object.keys())) {
        JSONObject entry = object.getJSONObject(key);
        // ...
    
  • 0

    我做了一个小的递归函数,遍历整个json对象并保存键路径及其值 .

    // 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

    下面的代码对我来说很好 . 如果可以进行调整,请帮助我 . 这甚至可以从嵌套的JSON对象获取所有键 .

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

相关问题