我使用一个名为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
}
}
发布于 2012-05-15 11:36:10
也许这会有所帮助:
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
}
}
发布于 2014-09-22 22:49:58
在我的例子中,我发现迭代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)));
}
发布于 2015-09-05 19:25:27
我将避免使用迭代器,因为它们可以在迭代期间添加/删除对象,也可以用于循环的干净代码。它将非常简洁&更少的代码行。
使用Java 8和Lamda Update 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);
});
}
使用旧方式更新2019年4月2日
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);
}
}
https://stackoverflow.com/questions/9151619
复制相似问题