gpt4 book ai didi

java - 如何将 joda-time 与 jaxb 绑定(bind)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:08:42 25 4
gpt4 key购买 nike

我正在上这样的课

@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 time 与 jaxb 绑定(bind),则需要一个适配器,但令人困惑的是我没有真正理解它。所以我开始了

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();

}

}

你能帮我完成它吗?提前致谢

最佳答案

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);

}
}

您还应该使用 @XmlJavaTypeAdapter 注释在 ScriptExecutionStatistics 中注释适当的字段/getter

@XmlJavaTypeAdapter(DateTimeAdapter.class)
@XmlAttribute
public DateTime getStart() {
return start;
}

关于java - 如何将 joda-time 与 jaxb 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com