Adrian
Adrian

Reputation: 167

JAXB list unmarshall don't show full list but just last object

So I have little problem. I have XML like this:

<Game>
    <GameTitle>Grand Theft Auto: Vice City</GameTitle>
    <Genres>
        <genre>Action</genre>
        <genre>Sandbox</genre>
    </Genres>
</Game>

And I want to dislpay in my JSP file "Action" and "Sandbox". But it shows me only "Sandbox". Here is my code:

@XmlRootElement(name = "Game")
public class Game {
    private String gameTitle;   
    private List<Genres> genres = new ArrayList<Genres>();

    public List<Genres> getGenres() {
        return genres;
    }

    @XmlElement(name = "Genres", type = Genres.class)
    public void setGenres(List<Genres> genres) {
        this.genres = genres;
    }

    public String getGameTitle() {
        return gameTitle;
    }

    @XmlElement(name = "GameTitle")
    public void setGameTitle(String gameTitle) {
        this.gameTitle = gameTitle;
    }
}

And my Genres class:

@XmlRootElement(name = "Genres")
public class Genres {
    private String genre;

    public String getGenre() {
        return genre;
    }

    @XmlElement(name = "genre")
    public void setGenre(String genre) {
        this.genre = genre;
    }
}

I tried to display it in JSP in this two way:

<c:forEach items="${game.genres}" var="item">
    ${item.genre}<br>
</c:forEach>

0: ${game.genres[0].genre}
1: ${game.genres[1].genre}
2: ${game.genres[2].genre}

But it returns me only Sandobx and 0: Sandbox 1: 2:. Somebody have maybe any idea what I'm doing wrong?

Upvotes: 2

Views: 45

Answers (2)

Solorad
Solorad

Reputation: 914

Your code is working if replace List<Genres> to List<String>.

Something like that:

@XmlRootElement(name = "Game")
@XmlAccessorType(XmlAccessType.FIELD)
public class Game {
    @XmlElement(name="GameTitle")
    private String gameTitle;

    @XmlElementWrapper(name="Genres")
    @XmlElement(name="genre")
    private List<String> genres;

    public List<String> getGenres() {
        return genres;
    }


    public void setGenres(List<String> genres) {
        this.genres = genres;
    }

    public String getGameTitle() {
        return gameTitle;
    }

    public void setGameTitle(String gameTitle) {
        this.gameTitle = gameTitle;
    }
}

The problem may be that your genre is simple String.

Upvotes: 2

AlexR
AlexR

Reputation: 115328

Your class is annotated incorrectly. Leave setter without annotation. Annotate getter as following using XmlElement and XmlElementWrapper.

@XmlElementWrapper( name="Genres" )
@XmlElement(name = "genre", type = Genres.class)
public List<Genres> getGenres() {
    return genres;
}

public void setGenres(List<Genres> genres) {
    this.genres = genres;
}

Upvotes: 0

Related Questions