Reputation: 21
I'm fairly new to Java and I'm trying to write an Iterator for my JSON-file.
But it keeps telling me that "incompatible types: JSONValue cannot be convert to JSONObject" at JSONObject authorNode = (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;
}
}
}
Can someone help me?
Upvotes: 2
Views: 1691
Reputation: 1211
authors.next(); returns an object of type JSONValue
private Iterator<JSONValue> authors;
But you are trying to cast it to an incompatible type (JSONObject)
JSONObject authorNode = (JSONObject) authors.next();
I would guess that your Iterator<JSONValue>
should instead be Iterator<JSONObject>
.
Upvotes: 2