如何用jaxb绑定joda-time

时间:2015-08-17 16:21:12

标签: java jaxb jodatime

我正在上这样的课程

@XmlRootElement(name = "executionStats")
public class ScriptExecutionStatistics {

private DateTime start;
private DateTime end;

public ScriptExecutionStatistics() { }

public ScriptExecutionStatistics(DateTime start, DateTime end) {
    this.start = start;
    this.end = end;
}

@XmlAttribute
public DateTime getStart() {
    return start;
}

public void setStart(DateTime start) {
    this.start = start;
}

@XmlAttribute
public DateTime getEnd() {
    return end;
}

public void setEnd(DateTime end) {
    this.end = end;
}

}

我想在xml中序列化它,所以它看起来像这样

<scriptExecutionStatistics start="17.08.2015 18:17:00" end="17.08.2015 18:18:00" />

我知道如果我想将joda时间与jaxb绑定,那么将需要一个适配器,但令人困惑的是我没有真正得到它。所以我已经开始了

public class DateTimeAdapter extends XmlAdapter<ScriptExecutionStatistics, DateTime>{
private static DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

@Override
public DateTime unmarshal(ScriptExecutionStatistics vt) throws Exception {
    throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public ScriptExecutionStatistics marshal(DateTime bt) throws Exception {
    ScriptExecutionStatistics stats = new ScriptExecutionStatistics();

}

}

请你帮我完成它。 提前致谢

1 个答案:

答案 0 :(得分:4)

DateTimeAdapter应该DateTime编组/解组String,例如public class DateTimeAdapter extends XmlAdapter<String, DateTime>{ private static DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); @Override public DateTime unmarshal(String vt) throws Exception { return dtf.parseDateTime(vt); } @Override public String marshal(DateTime bt) throws Exception { return dtf.print(bt); } }

ScriptExecutionStatistics

另外,您应该使用@XmlJavaTypeAdapter注释在@XmlJavaTypeAdapter(DateTimeAdapter.class) @XmlAttribute public DateTime getStart() { return start; } 中注释相应的字段/ getter

(:User)