[英]Rewrite Iterator from JSONObject to JSONArray
I have an iterator for JSONObjects
but unfortunately I get a JSONArray
from my JSON-data. 我有一个用于JSONObjects
的迭代器,但是很不幸,我从JSON数据中得到了一个JSONArray
。
Now I want to rewrite it. 现在我要重写它。 I'm pretty new to Java. 我对Java很陌生。 Can somebody tell me how to approach this? 有人可以告诉我该如何处理吗?
I use the json.simple library. 我使用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;
}
}
}
Due to lack of information about the structure of your JSON data, I assume the following: 由于缺乏有关JSON数据结构的信息,我假设以下内容:
JSONArray
object to call the constructor with 您有一个JSONArray
对象可使用 JSONArray
contains JSONObject
s 此JSONArray
包含JSONObject
JSONObject
s have got suitable key-value pairs 这些JSONObject
具有合适的键值对 In that case the following solution should work. 在这种情况下,以下解决方案应该起作用。 It takes advantage of the fact that JSONArray
itself is iteratable. 它利用了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;
}
}
EDIT: Given your actual input, the solution is simple: The array contains objects, which contain yet other arrays. 编辑:给定您的实际输入,解决方案很简单:数组包含对象,而对象又包含其他数组。 So for the above code to work, you have to do the following (where parsedJson
is that, what you get from your actual input file (as posted in dropbox): 因此, 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.