Search code examples
javanullpointerexceptionjaxb

XML String to Java Object NullPointerException


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.


Solution

  • When unmarshalling an XML with an implementation of the Unmarshaller interface, the operation first creates a default instance of the POJO with a no-args constructor, and then sets each property from the XML.

    In your case, the no-args constructor in the Recipes class does not initialize the List attribute recipes, leaving it to null. Therefore, when you attempt to iterate through the elements of the unmarshalled object rec, the operation throws a NUllPointerException.

    You could fix your code by:

    1. Initializing the List within the no-args constructor.
    @XmlRootElement
    public class Recipes {
        private List<Recipe> recipes;
    
        public Recipes(){
            this.recipes = new ArrayList();
        }
    
        public Recipes(List<Recipe> recipes){
            this.recipes = recipes;
        }
    
        ...
    }
    
    1. Initializing the List during declaration.
    @XmlRootElement
    public class Recipes {
        private List<Recipe> recipes = new ArrayList();
    
        public Recipes(){
            this.recipes;
        }
    
        public Recipes(List<Recipe> recipes){
            this.recipes = recipes;
        }
    
        ...
    }