我对 Java 相当陌生,我正在尝试为我的 JSON 文件编写一个迭代器。
但它一直告诉我“不兼容的类型:JSONValue 无法转换为 JSONObject”,位于 JSONObjectauthorNode = (JSONObject)authors.next();
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import mende.entity.Author;
public class JSONIteratorAuthor implements Iterator <Author> {
private Iterator<JSONValue> 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();
JSONObject authorNode = (JSONObject) authors.next();
a.setFirstName((String) authorNode.get("first_name"));
a.setLastName((String) authorNode.get("last_name"));
return a;
}
else {
return null;
}
}
}
有人可以帮助我吗?
最佳答案
authors.next();返回 JSONValue 类型的对象
private Iterator<JSONValue> authors;
但是您试图将其转换为不兼容的类型(JSONObject)
JSONObject authorNode = (JSONObject) authors.next();
我猜你的Iterator<JSONValue>
应该是 Iterator<JSONObject>
.
关于java - JSONValue 无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34618304/