JAX-RS JSON java.util.Date解组
我正在使用Jersey(jax-rs)构建一个REST丰富的应用程序 一切都很好,但我真的不明白如何配置日期和数字的JSON编组/解编选项 我有一个用户类:JAX-RS JSON java.util.Date解组,json,marshalling,jax-rs,unmarshalling,Json,Marshalling,Jax Rs,Unmarshalling,我正在使用Jersey(jax-rs)构建一个REST丰富的应用程序 一切都很好,但我真的不明白如何配置日期和数字的JSON编组/解编选项 我有一个用户类: @XmlRootElement public class User { private String username; private String password; private java.util.Date createdOn; // ... getters and setters } 当cre
@XmlRootElement
public class User {
private String username;
private String password;
private java.util.Date createdOn;
// ... getters and setters
}
当createdOn
属性被序列化时,我会得到如下字符串:“2010-05-12T00:00:00+02:00”,但我需要使用特定的日期模式,对日期进行marshall和unmarshall
有人知道怎么做吗?你得到的是标准的日期ISO 8601格式。Jersey将在服务器上为您解析它。对于javascript,这里有一个解析的方法
更新链接已失效:请尝试另一个解析器,请参阅。您可以编写一个XmlAdapter:
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class JsonDateAdapter extends XmlAdapter<String, Date> {
@Override
public Date unmarshal(String v) throws Exception {
// TODO convert from your format
}
@Override
public String marshal(Date v) throws Exception {
// TODO convert to your format
}
}
如果您不想使用适配器,或者需要对不同对象进行自定义编组,并且希望避免将适配器放在一起,那么还可以使用属性和bean模式:
private Date startDate;
@XmlTransient
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@XmlElement public String getStrStartDate() {
if (startDate == null) return null;
return "the string"; // the date converted to the format of your choice with a DateFormatter";
}
public void setStrStartDate(String strStartDate) throws Exception {
this.startDate = theDate; // the strStartDate converted to the a Date from the format of your choice with a DateFormatter;
}
谢谢你的回复!Javascript扩展还可以,但是我不知道如何控制marshall、unmarshall过程。你知道去哪里吗?非常感谢,DavideLink从那以后就去世了。经过几天的开发,我正在使用这两个功能强大的js库(),以ISO-8601格式将数据从服务器转换到服务器,并在需要时使用您的变通方法。当客户端和服务器之间存在不同的时区时,这种需求就会出现。在某些方面,日期是使用当地时间和格林尼治标准时间之间的差值自动计算出来的。当你需要一个日期时,这是一个很大的麻烦,它被压缩到午夜…@Davide我发现这个库对于解析各种字符串格式的日期以及计算给定时间戳上/之前的最后一个午夜非常有用。
private Date startDate;
@XmlTransient
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@XmlElement public String getStrStartDate() {
if (startDate == null) return null;
return "the string"; // the date converted to the format of your choice with a DateFormatter";
}
public void setStrStartDate(String strStartDate) throws Exception {
this.startDate = theDate; // the strStartDate converted to the a Date from the format of your choice with a DateFormatter;
}