如何遍历一个JSONObject?

我使用名为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 } } 

也许这将有助于:

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

对于我的情况,我发现迭代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))); } 

我将避免迭代器,因为他们可以在迭代过程中添加/删除对象,也可以为干净的代码使用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); } } 
 Iterator<JSONObject> iterator = jsonObject.values().iterator(); while (iterator.hasNext()) { jsonChildObject = iterator.next(); //DO what ever you whont with jsonChildObject String id = (String) jsonChildObject.get("id"); } 

首先把这个地方:

 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); // ... 

我做了一个小的递归函数,通过整个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(); } } 

使用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-

我曾经有一个JSON,因为它们是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作为父对象工作

不要相信我找不到比使用迭代器解决方案更简单,更安全的方法。

JSONObject的names ()方法返回一个JSONObject键的JSONArray,所以你可以简单地用循环遍历它:

 JSONArray keys = object.names (); for (int i = 0; i < keys.length (); ++i) { String key = keys.getString (i); // Here's your key }