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:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With