我有一个 JSONObjects
迭代器,但不幸的是我从 JSON 数据中得到了一个 JSONArray
。
现在我想重写它。我对 Java 还很陌生。有人可以告诉我如何处理这个问题吗?
我使用 json.simple 库。
public class JSONIteratorAuthor implements Iterator <Author> {
private Iterator<JSONObject> authors;
public JSONIteratorAuthor(JSONObject jsonObject){
this.authors = ((JSONArray) jsonObject.get("authors")).iterator();
}
@Override
public boolean hasNext() {
return this.authors.hasNext();
}
public Author next() {
if(this.hasNext()){
Author a = new Author(0, "", "");
JSONObject authorNode = (JSONObject) authors.next();
a.setFirstName((String) authorNode.get("first_name"));
a.setLastName((String) authorNode.get("last_name"));
return a;
}
else {
return null;
}
}
}
最佳答案
由于缺乏有关 JSON 数据结构的信息,我假设如下:
- 您有一个
JSONArray
对象来调用构造函数 - 此
JSONArray
包含JSONObject
- 这些
JSONObject
具有合适的键值对
在这种情况下,以下解决方案应该有效。它利用了 JSONArray
本身是可迭代的这一事实。
private Iterator<JSONObject> authors;
@SuppressWarnings("unchecked")
public JSONIteratorAuthor(JSONArray array){
authors = array.iterator();
}
@Override
public boolean hasNext() {
return authors.hasNext();
}
@Override
public Author next() {
if (hasNext()) {
Author a = new Author(0, "", "");
JSONObject authorNode = authors.next();
a.setFirstName((String) authorNode.get("first_name"));
a.setLastName((String) authorNode.get("last_name"));
return a;
}
else {
return null;
}
}
编辑:根据您的实际输入,解决方案很简单:该数组包含对象,其中包含其他数组。因此,要使上述代码正常工作,您必须执行以下操作(其中 parsedJson
是您从实际输入文件中获取的内容(如 dropbox 中发布的那样):
Iterator array = ((JSONArray) parsedJson).iterator();
while (array.hasNext()) {
JSONObject json = (JSONObject) array.next();
JSONArray authors = (JSONArray)json.get("authors");
JSONIteratorAuthor test = new JSONIteratorAuthor(authors);
while (test.hasNext()) {
System.out.println(test.next());
}
}
关于java - 将迭代器从 JSONObject 重写为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34897350/