开发者

JAX-RS JSON java.util.Date Unmarshall

开发者_如何学C

I'm using Jersey (jax-rs), to build a REST rich application.

Everything is great, but I don't really understand how to configure the JSON Marshalling/Unmarshalling options for dates and numbers.

I have a User class:

@XmlRootElement
public class User {
    private String username;
    private String password;
    private java.util.Date createdOn;

    // ... getters and setters
}

When the createdOn property is serialized, I get a string like this: '2010-05-12T00:00:00+02:00', but I need to use a specific date pattern, both to marshall and unmarshall dates.

Does someone know how to do that?


You could write an XmlAdapter:

  • http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html

Your particular XmlAdapter would look something like:

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
    }

}

Then on your date property set the following annotation:

@XmlJavaTypeAdapter(JsonDateAdapter.class)
public getDate() {
   return date;
}


What you get is a date ISO 8601 format, which is a standard. Jersey will parse it for you on the server. For javascript here is an extension to js date to parse that.

Update Link is dead: try another parser, see Help parsing ISO 8601 date in Javascript


If you do not want to have to play with the adaptors or you needed custom marshalling for different objects and want to avoid the adaptors alltogether, you could also play with the attributes and the bean pattern:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜