[英]Rewrite Iterator from JSONObject to JSONArray
我有一个用于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
上述代码正常工作,您必须执行以下操作(其中parsedJson
是从实际输入文件中获得的内容(如投递箱中所述):
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.