Error: java.lang.NullPointerException: Cannot invoke "java.util.List.iterator()" because "list" is null
Main class:
try {
jaxbContext = JAXBContext.newInstance(Recipes.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Recipes rec = (Recipes) jaxbUnmarshaller.unmarshal(new StringReader(xml));
List <Recipe> list = rec.getRecipes();
for (Recipe re: list){
System.out.println(re.getId());
}
} catch (JAXBException e) {
e.printStackTrace();
}
Recipe class:
@XmlRootElement(name = "results")
public class Recipe {
private int id;
private String title;
private Image image;
public Recipe(){}
public Recipe(int id, String title, Image image){
this.id = id;
this.title = title;
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
Recipes class:
@XmlRootElement
public class Recipes {
private List<Recipe> recipes;
public Recipes(){}
public Recipes(List<Recipe> recipes){
this.recipes = recipes;
}
@XmlElement
public List<Recipe> getRecipes() {
return recipes;
}
public void setRecipes(List<Recipe> recipes) {
this.recipes = recipes;
}
}
I'm trying to manage a xml string, that can be transformed in an array of objects. An error give me this message that the list is empty, I think, but i don't understand why, thanks for helping.
CodePudding user response:
It seems like that the unmarshal
with jaxbUnmarshaller
returns null to that list you're using later on. Can you maybe check what it returns with the debug?
Plus, your Recipes
class leaves the internal List
of Recipes
set to null if your class is instantiated with the no-args constructor. You might wanna type the following code within that empty constructor:
recipes = new ArrayList<>();