2010-06-16 53 views
7

我正在使用Jersey(jax-rs)構建一個REST豐富的應用程序。JAX-RS JSON java.util.Date Unmarshall

一切都很好,但我真的不明白如何爲日期和數字配置JSON編組/解組選項。

我有一個用戶等級:

@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',但我需要使用特定的日期模式,既可以編組日期也可以不編組。

有人知道該怎麼做嗎?

回答

2

你得到的是一個日期ISO 8601格式,這是一個標準。澤西將在服務器上爲你解析它。對於JavaScript,這裏是一個extension to js date來解析。

+0

感謝的到你的回覆! 好的JavaScript擴展,但是我不知道控制馬歇爾,unmarshall過程。 你知道在哪裏擴展球衣嗎? 非常感謝,Davide – Davide 2010-06-16 14:06:43

+0

鏈接已經去世。 – 2018-01-17 17:44:15

16

你可以寫一個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; 
} 
1

如果你不希望有適配器玩,或者你需要定製編組爲不同的對象,並希望避免適配器產品總數,你也可以用屬性和豆模式玩法:

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; 
} 
+0

經過幾天的開發之後,我使用了一個功能強大的js庫(http://www.datejs.com/),以ISO-8601格式將數據從服務器轉換爲服務器,並在需要時將使用你的工作。當客戶端與服務器之間存在不同的時區時,需求就會出現。在某些方面,使用當地時間和GMT之間的差異自動計算日期。當你需要一個日期,樹幹到午夜... ... – Davide 2011-02-15 23:44:00

+1

@Davide我發現[joda-time](http://joda-time.sourceforge.net/)庫有用的解析日期以各種字符串格式和計算給定時間戳之前/之前的最後一個午夜。 – 2012-02-02 10:08:36