[英]How to unmarshall JAX-RS Webservice response (JSON Array) correctly?
[英]JAX-RS JSON java.util.Date Unmarshall
我正在使用Jersey(jax-rs)来构建一个REST丰富的应用程序。
一切都很好,但我真的不明白如何为日期和数字配置JSON编组/解组选项。
我有一个User类:
@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',但是我需要使用特定的日期模式来编组和解组日期。
有人知道怎么做吗?
你可以写一个XmlAdapter:
您的特定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
}
}
然后在您的日期属性中设置以下注释:
@XmlJavaTypeAdapter(JsonDateAdapter.class)
public getDate() {
return date;
}
你得到的是日期ISO 8601格式,这是一个标准。 Jersey会在服务器上为你解析它。 对于javascript,这里是js date的扩展来解析它。
更新链接已死:尝试另一个解析器,请参阅帮助解析Javascript中的ISO 8601日期
如果您不想使用适配器,或者您需要为不同的对象进行自定义编组,并且想要完全避免使用适配器,那么您还可以使用属性和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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.