java - JSONValue 无法转换为 JSONObject

标签 java json

我对 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/

相关文章:

java - mkdir() 没有创建新目录

java - 空引用是一个类的实例吗?

Java:用于异步数据库写入的TaskExecutor?

java - AbsoluteLayout中的ImageView,如何设置ImageView的x,y坐标?

android - {"error": {"message" :"(#100) Missing message or attachment" ,"type" :"OAuthException" ,"code":100}}

java - 不同环境使用不同的 WSDL

ios - 如何减少responseJSON 中的样板文件,就像我使用 URLRequestConvertible 对相关的 Web 调用进行分组一样

不以m开头的MySQL Count值?

json - 使用 jq select 过滤 json 不起作用

json - 创建 IAM 策略时出现 MalformedPolicyDocument 错误