本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>
提问:如何迭代JSONObject
?
我使用一个名为JSONObject
的JSON库。
我知道如何迭代一个JSONArrays
,但是当我从Facebook解析数据时,没法获取JSONArrays
,只有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
}
}
复制代码
回答一
我会避免使用iterator
,因为它可以在迭代的时候新增/移除元素
使用Lambda
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);
}
}
复制代码
回答二
我想没有比在这个答案中使用iterator
更简单和安全的办法了。
JSONObjet 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
}
复制代码
回答三
- 使用包装类
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;
}
复制代码
- 简单迭代对象的
key
和value
for (String key : iteratorToIterable(object.keys())) {
JSONObject entry = object.getJSONObject(key);
// ...
复制代码
文章翻译自Stack Overflow:stackoverflow.com/questions/9…
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END