如何迭代JSONObject?我使用一个名为JSON的库JSONObject(如果需要的话,我不介意换)。我知道怎么迭代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
}}
3 回答
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
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
}}
墨色风雨
TA贡献1853条经验 获得超6个赞
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)));}
繁星coding
TA贡献1797条经验 获得超4个赞
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);
});}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);
}}添加回答
举报
0/150
提交
取消
