Showing posts with label JAXB. Show all posts
Showing posts with label JAXB. Show all posts

Friday, July 21, 2017

Serializing Java Objects with JAXB

Java Model

The model class Team

package j2s.team;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/* 
 * As the class Team is annotated with @XmlRootElement, JAXB transforms a Team 
 * instance into an XML document whose root element is <team> 
 */
@XmlRootElement(name="team")
@XmlType(propOrder={"name","description","playerList"})
@XmlAccessorType(XmlAccessType.FIELD)
public class Team {

 // fields
 private String name;
 private String description;

 @XmlElement(name = "player")
 @XmlElementWrapper(name = "players")
 private List<Player> playerList;

 public Team(String name, String description) {
  this.name = name;
  this.description = description;
  this.playerList = new ArrayList<Player>();
 }

 // default constructor required by JAXB
 public Team() {
  this("team name", "team descr");
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

 public List<Player> getPlayers() {
  return playerList;
 }

 public void setPlayers(List<Player> playerList) {
  this.playerList = playerList;
 }

 public void addPlayer(Player dev) {
  playerList.add(dev);
 }

 @Override
 public String toString() {
  return "Team [name=" + name + ", description=" + description + ", players=" + playerList + "]";
 }

}