[英]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.