简体   繁体   English

如何遍历 JSONObject?

[英]How to iterate over a JSONObject?

I use a JSON library called JSONObject (I don't mind switching if I need to).我使用一个名为JSONObject的 JSON 库(如果需要,我不介意切换)。

I know how to iterate over JSONArrays , but when I parse JSON data from Facebook I don't get an array, only a JSONObject , but I need to be able to access an item via its index, such as JSONObject[0] to get the first one, and I can't figure out how to do it.我知道如何迭代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
   }
}

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

for my case i found iterating the names() works well就我而言,我发现迭代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)));
}

I will avoid iterator as they can add/remove object during iteration, also for clean code use for loop.我将避免迭代器,因为它们可以在迭代期间添加/删除对象,也可以用于循环的干净代码使用。 it will be simply clean & fewer lines.这将是简单的清洁和更少的线条。

Using Java 8 and Lamda [Update 4/2/2019]使用 Java 8 和 Lamda [更新 4/2/2019]

import org.json.JSONObject;

public static void printJsonObject(JSONObject jsonObj) {
    jsonObj.keySet().forEach(keyStr ->
    {
        Object keyvalue = jsonObj.get(keyStr);
        System.out.println("key: "+ keyStr + " value: " + keyvalue);

        //for nested objects iteration if required
        //if (keyvalue instanceof JSONObject)
        //    printJsonObject((JSONObject)keyvalue);
    });
}

Using old way [Update 4/2/2019]使用旧方式 [更新 4/2/2019]

import org.json.JSONObject;

public static void printJsonObject(JSONObject jsonObj) {
    for (String keyStr : jsonObj.keySet()) {
        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);
    }
}

Original Answer原答案

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

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 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
   
}
Iterator<JSONObject> iterator = jsonObject.values().iterator();

while (iterator.hasNext()) {
 jsonChildObject = iterator.next();

 // Do whatever you want with jsonChildObject 

  String id = (String) jsonChildObject.get("id");
}

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

for(String key : jsonObject.keySet())

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:或者,如果您可以访问 Java8,只需:

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

Most of the answers here are for flat JSON structures, in case you have a JSON which might have nested JSONArrays or Nested JSONObjects, the real complexity arises.这里的大多数答案都是针对平面 JSON 结构的,如果您有一个 JSON 可能嵌套了 JSONArrays 或 Nested JSONObjects,那么真正的复杂性就会出现。 The following code snippet takes care of such a business requirement.以下代码片段负责处理此类业务需求。 It takes a hash map, and hierarchical JSON with both nested JSONArrays and JSONObjects and updates the JSON with the data in the hash map它需要一个哈希映射和带有嵌套 JSONArrays 和 JSONObjects 的分层 JSON,并使用哈希映射中的数据更新 JSON

public void updateData(JSONObject fullResponse, HashMap<String, String> mapToUpdate) {

    fullResponse.keySet().forEach(keyStr -> {
        Object keyvalue = fullResponse.get(keyStr);

        if (keyvalue instanceof JSONArray) {
            updateData(((JSONArray) keyvalue).getJSONObject(0), mapToUpdate);
        } else if (keyvalue instanceof JSONObject) {
            updateData((JSONObject) keyvalue, mapToUpdate);
        } else {
            // System.out.println("key: " + keyStr + " value: " + keyvalue);
            if (mapToUpdate.containsKey(keyStr)) {
                fullResponse.put(keyStr, mapToUpdate.get(keyStr));
            }
        }
    });

}

You have to notice here that the return type of this is void, but sice objects are passed as refernce this change is refelected to the caller.在这里你必须注意,this 的返回类型是 void,但是 sice 对象作为引用传递,这种变化会反映给调用者。

I made a small recursive function that goes through the entire json object and saves the key path and its value.我做了一个小的递归函数,它遍历整个 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();
    }
}

With Java 8 and lambda, cleaner:使用 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- https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#forEachRemaining-java.util.function.Consumer-

We used below set of code to iterate over JSONObject fields我们使用下面的代码集来迭代JSONObject字段

Iterator iterator = jsonObject.entrySet().iterator();

while (iterator.hasNext())  {
        Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
        processedJsonObject.add(entry.getKey(), entry.getValue());
}

I once had a json that had ids that needed to be incremented by one since they were 0-indexed and that was breaking Mysql auto-increment.我曾经有一个 json,它的 id 需要递增 1,因为它们是 0 索引的,这破坏了 Mysql 自动递增。

So for each object I wrote this code - might be helpful to someone:因此,对于我编写此代码的每个对象 - 可能对某人有所帮助:

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

usage:用法:

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

this can be transformed to work for JSONArray as parent object too这也可以转换为 JSONArray 作为父对象

I made my small method to log JsonObject fields, and get some stings.我做了我的小方法来记录 JsonObject 字段,并得到一些刺痛。 See if it can be usefull.看看能不能用。

object JsonParser {

val TAG = "JsonParser"
 /**
 * parse json object
 * @param objJson
 * @return  Map<String, String>
 * @throws JSONException
 */
@Throws(JSONException::class)
fun parseJson(objJson: Any?): Map<String, String> {
    val map = HashMap<String, String>()

    // If obj is a json array
    if (objJson is JSONArray) {
        for (i in 0 until objJson.length()) {
            parseJson(objJson[i])
        }
    } else if (objJson is JSONObject) {
        val it: Iterator<*> = objJson.keys()
        while (it.hasNext()) {
            val key = it.next().toString()
            // If you get an array
            when (val jobject = objJson[key]) {
                is JSONArray -> {
                    Log.e(TAG, " JSONArray: $jobject")
                    parseJson(jobject)
                }
                is JSONObject -> {
                    Log.e(TAG, " JSONObject: $jobject")
                    parseJson(jobject)
                }
                else -> {
                    Log.e(TAG, " adding to map: $key $jobject")
                    map[key] = jobject.toString()
                }
            }
        }
    }
    return map
}
}

The simpler approach is (just found on W3Schools):更简单的方法是(刚刚在 W3Schools 上找到):

let data = {.....}; // JSON Object
for(let d in data){
    console.log(d); // It gives you property name
    console.log(data[d]); // And this gives you its value
}

UPDATE更新

This approach works fine until you deal with the nested object so this approach will work.在您处理嵌套对象之前,此方法工作正常,因此此方法将起作用。

const iterateJSON = (jsonObject, output = {}) => {
  for (let d in jsonObject) {
    if (typeof jsonObject[d] === "string") {
      output[d] = jsonObject[d];
    }
    if (typeof jsonObject[d] === "object") {
      output[d] = iterateJSON(jsonObject[d]);
    }
  }
  return output;
}

And use the method like this并使用这样的方法

let output = iterateJSON(your_json_object);

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.这甚至从嵌套的 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;
}

This is is another working solution to the problem:这是该问题的另一个有效解决方案:

public void test (){

    Map<String, String> keyValueStore = new HasMap<>();
    Stack<String> keyPath = new Stack();
    JSONObject json = new JSONObject("thisYourJsonObject");
    keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
    for(Map.Entry<String, String> map : keyValueStore.entrySet()) {
        System.out.println(map.getKey() + ":" + map.getValue());
    }   
}

public Map<String, String> getAllXpathAndValueFromJsonObject(JSONObject json, Map<String, String> keyValueStore, Stack<String> keyPath) {
    Set<String> jsonKeys = json.keySet();
    for (Object keyO : jsonKeys) {
        String key = (String) keyO;
        keyPath.push(key);
        Object object = json.get(key);

        if (object instanceof JSONObject) {
            getAllXpathAndValueFromJsonObject((JSONObject) object, keyValueStore, keyPath);
        }

        if (object instanceof JSONArray) {
            doJsonArray((JSONArray) object, keyPath, keyValueStore, json, key);
        }

        if (object instanceof String || object instanceof Boolean || object.equals(null)) {
            String keyStr = "";

            for (String keySub : keyPath) {
                keyStr += keySub + ".";
            }

            keyStr = keyStr.substring(0, keyStr.length() - 1);

            keyPath.pop();

            keyValueStore.put(keyStr, json.get(key).toString());
        }
    }

    if (keyPath.size() > 0) {
        keyPath.pop();
    }

    return keyValueStore;
}

public void doJsonArray(JSONArray object, Stack<String> keyPath, Map<String, String> keyValueStore, JSONObject json,
        String key) {
    JSONArray arr = (JSONArray) object;
    for (int i = 0; i < arr.length(); i++) {
        keyPath.push(Integer.toString(i));
        Object obj = arr.get(i);
        if (obj instanceof JSONObject) {
            getAllXpathAndValueFromJsonObject((JSONObject) obj, keyValueStore, keyPath);
        }

        if (obj instanceof JSONArray) {
            doJsonArray((JSONArray) obj, keyPath, keyValueStore, json, key);
        }

        if (obj instanceof String || obj instanceof Boolean || obj.equals(null)) {
            String keyStr = "";

            for (String keySub : keyPath) {
                keyStr += keySub + ".";
            }

            keyStr = keyStr.substring(0, keyStr.length() - 1);

            keyPath.pop();

            keyValueStore.put(keyStr , json.get(key).toString());
        }
    }
    if (keyPath.size() > 0) {
        keyPath.pop();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM