Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS JSON java.util.Date Unmarshall

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?

like image 988
Davide Avatar asked Jun 16 '10 10:06

Davide


3 Answers

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;
}
like image 168
bdoughan Avatar answered Jan 08 '23 01:01

bdoughan


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

like image 34
redben Avatar answered Jan 08 '23 01:01

redben


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;
}
like image 33
David Costa Faidella Avatar answered Jan 08 '23 00:01

David Costa Faidella