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

当前回答

我将避免迭代器,因为它们可以在迭代过程中添加/删除对象,也可以为循环使用干净的代码。它将是简单的干净和更少的行。

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

使用旧方式[更新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);
    }
}

原来的答案

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

其他回答

也许这个会有帮助:

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

我曾经有一个json,有id需要加1,因为他们是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作为父对象

Iterator<JSONObject> iterator = jsonObject.values().iterator();

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

 // Do whatever you want with jsonChildObject 

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

我让我的小方法记录JsonObject字段,并获得一些刺。看看它是否有用。

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

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

for(String key : jsonObject.keySet())