JAXB: Mapping XML attribute value to custom data type



Suppose you have an XML containing an element as follows:



<card expirydate="012017"> <!-- various attributes exists but it's unnecessary for this case.


As you can see the first 2 characters dictates the month and the last 4 digits represents the year.


I will like to model it to a Month object like so:



/**
* @author Buhake Sindi
* @since 19 January 2015
*
*/
public class Month implements Serializable {

/**
*
*/
private static final long serialVersionUID = -3746059271757081350L;

private int month;
private int year;

/**
*
*/
public Month() {
// TODO Auto-generated constructor stub
}

/**
* @param month
* @param year
*/
public Month(int month, int year) {
super();
PreConditions.checkArgument(month >= 1 && month <= 12, "Invalid month specified.");
this.month = month;
this.year = year;
}

/**
* @return the month
*/
public int getMonth() {
return month;
}

/**
* @param month the month to set
*/
public void setMonth(int month) {
this.month = month;
}

/**
* @return the year
*/
public int getYear() {
return year;
}

/**
* @param year the year to set
*/
public void setYear(int year) {
this.year = year;
}
}


What type of Converter do I use that maps an attribute to an Object and vice versa in JAXB?


No comments:

Post a Comment