jaxb 解组时间戳 [英] jaxb unmarshal timestamp
本文介绍了jaxb 解组时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法让 JAXB 在 Resteasy JAX-RS 服务器应用程序中解组时间戳.
I cannot get JAXB to unmarshal a timestamp in a Resteasy JAX-RS server application.
我的班级是这样的:
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "foo")
public final class Foo {
// Other fields omitted
@XmlElement(name = "timestamp", required = true)
protected Date timestamp;
public Foo() {}
public Date getTimestamp() {
return timestamp;
}
public String getTimestampAsString() {
return (timestamp != null) ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp) : null;
}
public void setTimestamp(final Date timestamp) {
this.timestamp = timestamp;
}
public void setTimestamp(final String timestampAsString) {
try {
this.timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timestampAsString);
} catch (ParseException ex) {
this.timestamp = null;
}
}
}
有什么想法吗?
谢谢.
推荐答案
JAXB 可以处理 java.util.Date 类.但是它期望格式:
JAXB can handle the java.util.Date class. However it expects the format:
yyyy-MM-dd'T'HH:mm:ss"代替yyyy-MM-dd HH:mm:ss"
"yyyy-MM-dd'T'HH:mm:ss" instead of "yyyy-MM-dd HH:mm:ss"
如果您想使用该日期格式,我建议您使用 XmlAdapter,它看起来类似于以下内容:
If you want to use that date format I would suggest using an XmlAdapter, it would look something like the following:
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class DateAdapter extends XmlAdapter<String, Date> {
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public String marshal(Date v) throws Exception {
return dateFormat.format(v);
}
@Override
public Date unmarshal(String v) throws Exception {
return dateFormat.parse(v);
}
}
然后您将在时间戳属性上指定此适配器:
You would then specify this adapter on your timestamp property:
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "foo")
public final class Foo {
// Other fields omitted
@XmlElement(name = "timestamp", required = true)
@XmlJavaTypeAdapter(DateAdapter.class)
protected Date timestamp;
public Foo() {}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(final Date timestamp) {
this.timestamp = timestamp;
}
}
这篇关于jaxb 解组时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文