JAXB:将 XML 属性值映射到自定义数据类型
JAXB: Mapping XML attribute value to custom data type
假设您有一个 XML 包含如下元素:
<card expirydate="012017"> <!-- various attributes exists but it's unnecessary for this case.
如您所见,前 2 个字符表示月份,后 4 位数字表示年份。
我想将其建模为 Month
对象,如下所示:
/**
* @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;
}
}
在 JAXB 中,我使用什么类型的 Converter/Adapter 将属性映射到对象,反之亦然?
您将为此用例创建一个 XmlAdapter
,将 Month
to/from 转换为 String
.
public class MonthAdapter extends XmlAdapter<String, Month>
然后在 marshal/unmarshal 方法中放置您自己的自定义逻辑,用于在 Month
和 String
之间进行转换。
假设您有一个 XML 包含如下元素:
<card expirydate="012017"> <!-- various attributes exists but it's unnecessary for this case.
如您所见,前 2 个字符表示月份,后 4 位数字表示年份。
我想将其建模为 Month
对象,如下所示:
/**
* @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;
}
}
在 JAXB 中,我使用什么类型的 Converter/Adapter 将属性映射到对象,反之亦然?
您将为此用例创建一个 XmlAdapter
,将 Month
to/from 转换为 String
.
public class MonthAdapter extends XmlAdapter<String, Month>
然后在 marshal/unmarshal 方法中放置您自己的自定义逻辑,用于在 Month
和 String
之间进行转换。